Md5Utils.java 1.2 KB

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