MD5加密

来源:互联网 发布:广通软件怎么样 编辑:程序博客网 时间:2024/06/05 22:29

importjava.security.MessageDigest;

public class MD5Util {

    public final static StringMD5(String s) {
        charhexDigits[]= {'0','1','2','3','4','o','M','s','a','f',
                '5', '6','7','8', 's', 'F', 'e','P','a', 'W',
                'A', 'B','C','D', 'E', 'F', 'L','l','G', 'g'};
        try{
            byte[]btInput = s.getBytes();

            //获得MD5摘要算法的MessageDigest 对象 
           
MessageDigestmdInst = MessageDigest.getInstance("MD5");

            //使用指定的字节更新摘要 
           
mdInst.update(btInput);

            //获得密文 
           
byte[] md= mdInst.digest();

            //把密文转换成十六进制的字符串形式 
           
intj= md.length;  // 记录md的长度
           
charstr[]= new char[j* 2];   // 存储结果用
           
intk= 0;
            for(inti=0; i< j; i++) {
                bytebyte0= md[i];
                str[k++] =hexDigits[byte0 >>> 4 &0xf]; //数组中对应的十六进制数放入str中
               
str[k++]= hexDigits[byte0 & 0xf];
            }
            returnnew String(str);   // 返回加密后的字符串
       
} catch(Exceptione) {
           e.printStackTrace();
            returnnull;    // 如果有异常返回null
       
}
    }

}