天天看点

java 密码MD5加密

package com.sunnylocus.util;  

import java.security.messagedigest;  

/**  

 * 对密码进行加密和验证的类 

 */  

public class cipherutil{  

    //十六进制下数字到字符的映射数组  

    private final static string[] hexdigits = {"0", "1", "2", "3", "4",  

        "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};  

    /** * 把inputstring加密     */  

    public static string generatepassword(string inputstring){  

        return encodebymd5(inputstring);  

    }  

      /** 

       * 验证输入的密码是否正确 

     * @param password    加密后的密码 

     * @param inputstring    输入的字符串 

     * @return    验证结果,true:正确 false:错误 

     */  

    public static boolean validatepassword(string password, string inputstring){  

        if(password.equals(encodebymd5(inputstring))){  

            return true;  

        } else{  

            return false;  

        }  

    /**  对字符串进行md5加密     */  

    private static string encodebymd5(string originstring){  

        if (originstring != null){  

            try{  

                //创建具有指定算法名称的信息摘要  

                messagedigest md = messagedigest.getinstance("md5");  

                //使用指定的字节数组对摘要进行最后更新,然后完成摘要计算  

                byte[] results = md.digest(originstring.getbytes());  

                //将得到的字节数组变成字符串返回  

                string resultstring = bytearraytohexstring(results);  

                return resultstring.touppercase();  

            } catch(exception ex){  

                ex.printstacktrace();  

            }  

        return null;  

    /**  

     * 转换字节数组为十六进制字符串 

     * @param     字节数组 

     * @return    十六进制字符串 

    private static string bytearraytohexstring(byte[] b){  

        stringbuffer resultsb = new stringbuffer();  

        for (int i = 0; i < b.length; i++){  

            resultsb.append(bytetohexstring(b[i]));  

        return resultsb.tostring();  

    /** 将一个字节转化成十六进制形式的字符串     */  

    private static string bytetohexstring(byte b){  

        int n = b;  

        if (n < 0)  

            n = 256 + n;  

        int d1 = n / 16;  

        int d2 = n % 16;  

        return hexdigits[d1] + hexdigits[d2];  

}  

java代码  

java 密码MD5加密

public class main {  

    public static void main(string[] args) {  

        string pwd1="123";  

        string pwd2="";  

        cipherutil cipher = new cipherutil();  

        system.out.println("未加密的密码:"+pwd1);  

        //将123加密  

        pwd2 = cipher.generatepassword(pwd1);  

        system.out.println("加密后的密码:"+pwd2);  

        system.out.print("验证密码是否下确:");  

        if(cipher.validatepassword(pwd2, pwd1)) {  

            system.out.println("正确");  

        else {  

            system.out.println("错误");  

结果输出:

java 密码MD5加密

未加密的密码:123  

加密后的密码:202cb962ac59075b964b07152d234b70  

验证密码是否下确:正确