Md5Utils.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.ruoyi.common.utils.sign;
  2. import java.nio.charset.StandardCharsets;
  3. import java.security.MessageDigest;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. /**
  7. * Md5加密方法
  8. *
  9. * @author ruoyi
  10. */
  11. public class Md5Utils
  12. {
  13. private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
  14. private static byte[] md5(String s)
  15. {
  16. MessageDigest algorithm;
  17. try
  18. {
  19. algorithm = MessageDigest.getInstance("MD5");
  20. algorithm.reset();
  21. algorithm.update(s.getBytes("UTF-8"));
  22. byte[] messageDigest = algorithm.digest();
  23. return messageDigest;
  24. }
  25. catch (Exception e)
  26. {
  27. log.error("MD5 Error...", e);
  28. }
  29. return null;
  30. }
  31. private static final String toHex(byte hash[])
  32. {
  33. if (hash == null)
  34. {
  35. return null;
  36. }
  37. StringBuffer buf = new StringBuffer(hash.length * 2);
  38. int i;
  39. for (i = 0; i < hash.length; i++)
  40. {
  41. if ((hash[i] & 0xff) < 0x10)
  42. {
  43. buf.append("0");
  44. }
  45. buf.append(Long.toString(hash[i] & 0xff, 16));
  46. }
  47. return buf.toString();
  48. }
  49. public static String hash(String s)
  50. {
  51. try
  52. {
  53. return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
  54. }
  55. catch (Exception e)
  56. {
  57. log.error("not supported charset...{}", e);
  58. return s;
  59. }
  60. }
  61. }