MD5加密——3行代码

来源:互联网 发布:怎么能做网络写手 编辑:程序博客网 时间:2024/05/20 07:14

这是其他人博客看见的3行代码MD5加密:

public static String getMD5(String str) {    try {        // 生成一个MD5加密计算摘要        MessageDigest md = MessageDigest.getInstance("MD5");        // 计算md5函数        md.update(str.getBytes());        // digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符        // BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值        return new BigInteger(1, md.digest()).toString(16);    } catch (Exception e) {        e.printStackTrace();    }}

注:经实践发现,由于中间获取的byte数组是先转为BigInteger再转为String。所以,当加密后的MD5字符串前几位是0的话,这些0将丢失,位数不足32位,需要在前方进行补足0。

这边另外提供一个修改后的MessageDigest 进行MD5加密的方法。

public static String parseStrToMd5L32(String str){     String reStr = null;     try {       MessageDigest md5 = MessageDigest.getInstance("MD5");       byte[] bytes = md5.digest(str.getBytes());       StringBuffer stringBuffer = new StringBuffer();       for (byte b : bytes){         int bt = b&0xff;         if (bt < 16){           stringBuffer.append(0);         }          stringBuffer.append(Integer.toHexString(bt));       }       reStr = stringBuffer.toString();     } catch (NoSuchAlgorithmException e) {       e.printStackTrace();     }     return reStr;   } 
0 0
原创粉丝点击