CheckSumBuilder.java 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package com.yihu.jw.utils;
  2. import java.security.MessageDigest;
  3. public class CheckSumBuilder {
  4. // 计算并获取CheckSum
  5. public static String getCheckSum(String appSecret, String nonce, String curTime) {
  6. return encode("sha1", appSecret + nonce + curTime);
  7. }
  8. // 计算并获取md5值
  9. public static String getMD5(String requestBody) {
  10. return encode("md5", requestBody);
  11. }
  12. private static String encode(String algorithm, String value) {
  13. if (value == null) {
  14. return null;
  15. }
  16. try {
  17. MessageDigest messageDigest
  18. = MessageDigest.getInstance(algorithm);
  19. messageDigest.update(value.getBytes());
  20. return getFormattedText(messageDigest.digest());
  21. } catch (Exception e) {
  22. throw new RuntimeException(e);
  23. }
  24. }
  25. private static String getFormattedText(byte[] bytes) {
  26. int len = bytes.length;
  27. StringBuilder buf = new StringBuilder(len * 2);
  28. for (int j = 0; j < len; j++) {
  29. buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
  30. buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
  31. }
  32. return buf.toString();
  33. }
  34. private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
  35. '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  36. }