今天项目中遇到调一接口 验证 sign 怎么验证 都很少。检查 发现 相同的内容 两次MD5 结果不同。算法
把包打开 检查了一下 MD5 算法。一看才知道,写这个代码的人 没有 指定字符集app
public class MD5Digest {编码
private static MessageDigest md5=null;接口
public static String getDigest(String msg) throws UnsupportedEncodingException, NoSuchAlgorithmException {md5
if(null == md5) {get
md5=MessageDigest.getInstance("MD5");it
}io
byte[] byteArray=null;字符编码
byteArray=msg.getBytes(); class
byte[] md5Bytes=md5.digest(byteArray);
StringBuffer hexValue=new StringBuffer();
for(int i=0; i < md5Bytes.length; i++) {
int val=((int)md5Bytes[i]) & 0xff;
if(val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
byteArray=msg.getBytes();
在不一样的环境下得到的结果多是不同的,这样也形成不少MD5结果不同。
保证在不一样环境下MD5结果相同那么必须使用相同的字符编码,好比:byteArray=msg.getBytes("UTF-8");