CheckoutUtil.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package com.care.common.util;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.util.Arrays;
  5. import java.util.Formatter;
  6. public class CheckoutUtil {
  7. // 与测试账号接口配置信息中的Token要一致
  8. private static String token = "yuanbaoBss734jHsToken";
  9. /**
  10. * 验证签名
  11. * @param signature
  12. * @param timestamp
  13. * @param nonce
  14. * @return
  15. */
  16. public static boolean checkSignature(String signature, String timestamp, String nonce) {
  17. String[] arr = new String[] { token, timestamp, nonce };
  18. Arrays.sort(arr);// 将token、timestamp、nonce三个参数进行字典序排序
  19. StringBuilder content = new StringBuilder();
  20. for (int i = 0; i < arr.length; i++) {
  21. content.append(arr[i]);
  22. }
  23. MessageDigest md = null;
  24. String tmpStr = null;
  25. try {
  26. md = MessageDigest.getInstance("SHA-1");
  27. // 将三个参数字符串拼接成一个字符串进行sha1加密
  28. byte[] digest = md.digest(content.toString().getBytes());
  29. tmpStr = byteToHex(digest );
  30. } catch (NoSuchAlgorithmException e) {
  31. e.printStackTrace();
  32. }
  33. // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
  34. return tmpStr != null ? tmpStr.equals(signature) : false;
  35. }
  36. //十六进制字节数组转为字符串
  37. private static String byteToHex(final byte[] hash) {
  38. Formatter formatter = new Formatter();
  39. for (byte b : hash) {
  40. formatter.format("%02x", b);
  41. }
  42. String result = formatter.toString();
  43. formatter.close();
  44. return result;
  45. }
  46. }