欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MD5加密实例

程序员文章站 2022-03-01 18:43:32
...

实例一:

加密工具类:

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