SHA1.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package com.happy.Unitil_nsh;
  2. import java.security.MessageDigest;
  3. /**
  4. * 微信SHA1算法
  5. * @author lujunjie
  6. * @date 2018/03/01
  7. */
  8. public final class SHA1 {
  9. private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  10. /**
  11. * 将字节并格式化
  12. * @param bytes 原始字节
  13. * @return 格式化字节
  14. */
  15. private static String getFormattedText(byte[] bytes) {
  16. int len = bytes.length;
  17. StringBuilder buf = new StringBuilder(len * 2);
  18. // 把密文转换成十六进制的字符串形式
  19. for (int j = 0; j < len; j++) {
  20. buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
  21. buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
  22. }
  23. return buf.toString();
  24. }
  25. public static String encode(String str) {
  26. if (str == null) {
  27. return null;
  28. }
  29. try {
  30. MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
  31. messageDigest.update(str.getBytes());
  32. return getFormattedText(messageDigest.digest());
  33. } catch (Exception e) {
  34. throw new RuntimeException(e);
  35. }
  36. }
  37. }