Md5Utils.java 1.5 KB

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