记录下MD5加密遇到的坑

错误的写法:

public static String md5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有md5这个算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
// 如果生成数字未满32位,需要前面补0
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}

----这种写法会导致 有一定几率出现31位加密报文,坑的无话可说!这时候只能将json字符串报文中的双引号 replace 成单引号 成功解决,需要判断2种情况,双引号不行再换单引号,不然单引号也会出现31位加密报文,坑啊,说到底还是上面的加密算法有问题。

正确的写法:

public static String MD5(String sourceStr) {
try {
// 获得MD5摘要算法的 MessageDigest对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(sourceStr.getBytes());
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
StringBuffer buf = new StringBuffer();
for (int i = 0; i < md.length; i++) {
int tmp = md[i];
if (tmp < 0)
tmp += 256;
if (tmp < 16)
buf.append("0");
buf.append(Integer.toHexString(tmp));
}
// return buf.toString().substring(8, 24);// 16位加密
return buf.toString();// 32位加密
} catch (Exception e) {
throw new RuntimeException("没有md5这个算法!");
}
}

-----这个会在最前面补上一个0,构成32位加密报文

原文地址:https://www.cnblogs.com/yw-ah/p/7027858.html