JAVA MD5 加密算法

MD5加密算法严密,安全性较高,广泛应用于系统身份验证、文件完整性验证中。Java API中java.security包中包含MessageDigest类,可以实现MD5算法的简单应用,譬如将指定的普通明文转换成MD5密码,参考源代码如下:

/* *************************************************************
 * Project: bobToolkit


 * Package: bob.sec.MD5


 * Filename: MD5Util.java


 * Created by BobChen on 2007-3-29


 *
 *  Date      Author         Description
 * 2007-3-29    BobChen        init: object MD5Util
 * ***********************************************************/
package bob.sec.MD5;

import java.security.MessageDigest;

public class MD5Util {
    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[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.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) {
            // e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.print(MD5Util.MD5("AusITcim#1485"));
    }

}

---------- 运行 ----------
EF277661A4C821C9007ACB52E1D883EC
输出完成 (耗时 0 秒) - 正常终止
 

 

----------------------JSP页面调用-------------------------------

----------

String u_password=new String(request.getParameter("u_password").getBytes("ISO-8859-1"));

u_password=(new MD5Util().MD5(u_password));


---------

String u_id=new String(request.getParameter("u_id").getBytes("ISO-8859-1"));


String u_password=new String(request.getParameter("u_password").getBytes("ISO-8859-1"));


u_password=(new MD5Util().MD5(u_password));

你可能感兴趣的:(JAVA技术,java,string,byte,exception,算法,加密)