MD5加密实例

实例一:

加密工具类:

package com.cz.md5;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

	public static String getMD5Str(String str) { 
		MessageDigest messageDigest = null;  
		  
	    try {  
	        messageDigest = MessageDigest.getInstance("MD5");  
	
	        messageDigest.reset();  
	
	        messageDigest.update(str.getBytes("UTF-8"));  
	    } catch (NoSuchAlgorithmException e) {  
	        System.out.println("NoSuchAlgorithmException caught!");  
	        System.exit(-1);  
	    } catch (UnsupportedEncodingException e) {  
	        e.printStackTrace();  
	    }  
	
	    byte[] byteArray = messageDigest.digest();  
	
	    StringBuffer md5StrBuff = new StringBuffer();  
	
	    for (int i = 0; i < byteArray.length; i++) {              
	        if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
	            md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
	        else  
	            md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
	    }  
	
	    return md5StrBuff.toString(); 
	}
}


测试类:

package com.cz.md5;

public class MD5Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//设置需要加密的字符串
		String password="abc123456";
		MD5Util util = null;
		String MD5password=util.getMD5Str(password);
		System.out.println("加密后的MD5码:"+MD5password);

	}

}

 

控制台输出:

加密后的MD5码:0659c7992e268962384eb17fafe88364

 

实例二(推荐):

package com.cz.test;

import java.security.MessageDigest;

public class TestMD5 {

    /**
     * @param args
     */
    public final static String MD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(MD5("abc123456"));
    }

}
 

 

控制台输出:

0659c7992e268962384eb17fafe88364

 

你可能感兴趣的:(MD5)