Md5Utils.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package com.kmall.admin.haikong.utils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.io.UnsupportedEncodingException;
  5. import java.security.MessageDigest;
  6. /**
  7. * Md5加密方法
  8. *
  9. * @author cadmin
  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("UTF-8"), "UTF-8");
  54. }
  55. catch (Exception e)
  56. {
  57. log.error("not supported charset...{}", e);
  58. return s;
  59. }
  60. }
  61. /**
  62. * MD5加密,返回32位密文
  63. * @param plainText
  64. * @return String
  65. * @throws UnsupportedEncodingException
  66. */
  67. public static String encryption(String plainText){
  68. String re_md5 = new String();
  69. try {
  70. MessageDigest md = MessageDigest.getInstance("MD5");
  71. md.update(plainText.getBytes("UTF-8"));
  72. byte b[] = md.digest();
  73. int i;
  74. StringBuffer buf = new StringBuffer("");
  75. for (int offset = 0; offset < b.length; offset++) {
  76. i = b[offset];
  77. if (i < 0)
  78. i += 256;
  79. if (i < 16)
  80. buf.append("0");
  81. buf.append(Integer.toHexString(i));
  82. }
  83. re_md5 = buf.toString();
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87. return re_md5;
  88. }
  89. }