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

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

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

public static String MD5(String input) {

try {

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

MessageDigest mdInst = MessageDigest.getInstance("MD5");

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

mdInst.update(input.getBytes("utf-8"));

// 获得密文

byte[] md = mdInst.digest();

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

StringBuffer hexString = new StringBuffer();

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

for (int i = 0; i < md.length; i++) {

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

if (shaHex.length() < 2) {

hexString.append(0);

}

hexString.append(shaHex);

}

return hexString.toString();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return "";

}

猜你喜欢

转载自washingtin.iteye.com/blog/2319404