MD5Util.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package com.usky.utils;
  2. import java.io.UnsupportedEncodingException;
  3. import java.math.BigInteger;
  4. import java.security.MessageDigest;
  5. import java.security.NoSuchAlgorithmException;
  6. public class MD5Util {
  7. public final static String MD5(String s){
  8. char hexDigits[] ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  9. try{
  10. byte[] btInput = s.getBytes();
  11. MessageDigest mdInst = MessageDigest.getInstance("MD5");
  12. mdInst.update(btInput);
  13. byte[] md = mdInst.digest();
  14. int j = md.length;
  15. char str[] = new char[j*2];
  16. int k = 0;
  17. for(int i=0;i<j;i++){
  18. byte byte0 = md[i];
  19. str[k++] = hexDigits[byte0 >>> 4 & 0xf];
  20. str[k++] = hexDigits[byte0 & 0xf];
  21. }
  22. return new String(str);
  23. } catch (Exception e){
  24. return null;
  25. }
  26. }
  27. public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{
  28. byte[] secretBytes = null;
  29. MessageDigest md5=MessageDigest.getInstance("MD5");
  30. md5.update(str.getBytes());
  31. secretBytes = md5.digest();
  32. String newstr = new BigInteger(1,secretBytes).toString(16);
  33. for(int i=0;i<32-newstr.length();i++)
  34. newstr = "0"+newstr;
  35. return newstr;
  36. }
  37. }