Java MD5

 Java Md5 实现:

 

 

Java代码 复制代码 收藏代码
  1. import java.io.FileInputStream;
  2. import java.io.UnsupportedEncodingException;
  3. import java.math.BigInteger;
  4. import java.security.MessageDigest;
  5. import java.security.NoSuchAlgorithmException;
  6.  
  7. public class MD5 {
  8. public static String getMD5(String input) {
  9. byte[] source;
  10. try {
  11. //Get byte according by specified coding.
  12. source = input.getBytes("UTF-8");
  13. } catch (UnsupportedEncodingException e) {
  14. source = input.getBytes();
  15. }
  16. String result = null;
  17. char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7',
  18. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  19. try {
  20. MessageDigest md = MessageDigest.getInstance("MD5");
  21. md.update(source);
  22. //The result should be one 128 integer
  23. byte temp[] = md.digest();
  24. char str[] = new char[16 * 2];
  25. int k = 0;
  26. for (int i = 0; i < 16; i++) {
  27. byte byte0 = temp[i];
  28. str[k++] = hexDigits[byte0 >>> 4 & 0xf];
  29. str[k++] = hexDigits[byte0 & 0xf];
  30. }
  31. result = new String(str);
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. return result;
  36. }
  37.  
  38. public static void main(String[] args) throws NoSuchAlgorithmException {
  39. System.out.println(getMD5("Javarmi.com"));
  40. }
  41. }
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
public class MD5 {
    public static String getMD5(String input) {
        byte[] source;
        try {
            //Get byte according by specified coding.
            source = input.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            source = input.getBytes();
        }
        String result = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source);
            //The result should be one 128 integer
            byte temp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = temp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            result = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println(getMD5("Javarmi.com"));
    }
}
代码copy来自于 http://www.asjava.com/core-java/java-md5-example/

你可能感兴趣的:(java)