md5解析出的结果不一致的问题

时间:2025-03-19 14:01:40

问题:md5在不同的环境下(例如:eclipse或intellij或tomcat下跑同样的代码),md5后的值不一样

 

解决方法:在参数转成字节的时候,统一字符集,下面方法红色部份

 

public static String MD5(String input) {

try {

// 获得MD5摘要算法的 MessageDigest 对象

MessageDigest mdInst = ("MD5");

// 使用指定的字节更新摘要

(("utf-8"));

// 获得密文

byte[] md = ();

// 把密文转换成十六进制的字符串形式

StringBuffer hexString = new StringBuffer();

// 字节数组转换为 十六进制 数

for (int i = 0; i < ; i++) {

String shaHex = (md[i] & 0xFF);

if (() < 2) {

(0);

}

(shaHex);

}

return ();

} catch (NoSuchAlgorithmException e) {

();

} catch (UnsupportedEncodingException e) {

();

}

return "";

}