Md5Util.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package com.huaxu.common;
  2. import java.security.MessageDigest;
  3. public class Md5Util {
  4. private static byte[] md5(String s){
  5. MessageDigest algorithm;
  6. try{
  7. algorithm = MessageDigest.getInstance("MD5");
  8. algorithm.reset();
  9. algorithm.update(s.getBytes("UTF-8"));
  10. byte[] messageDigest = algorithm.digest();
  11. return messageDigest;
  12. }
  13. catch (Exception e){
  14. }
  15. return null;
  16. }
  17. private static final String toHex(byte hash[]){
  18. if (hash == null){
  19. return null;
  20. }
  21. StringBuffer buf = new StringBuffer(hash.length * 2);
  22. int i;
  23. for (i = 0; i < hash.length; i++){
  24. if ((hash[i] & 0xff) < 0x10){
  25. buf.append("0");
  26. }
  27. buf.append(Long.toString(hash[i] & 0xff, 16));
  28. }
  29. return buf.toString();
  30. }
  31. public static String hash(String s){
  32. try{
  33. return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
  34. }
  35. catch (Exception e){
  36. return s;
  37. }
  38. }
  39. }