[英]MD5 results are different between DigestUtils and MessageDigest
I have tried to use java.security.MessageDigest or org.apache.commons.codec.digest.DigestUtils to do md5, but there comes out different results.我曾尝试使用 java.security.MessageDigest 或 org.apache.commons.codec.digest.DigestUtils 来做 md5,但结果不同。
The sample code as below:示例代码如下:
public static void main( String[] args )
{
System.out.println("MessageDigest: " + MD5("12345") );
MessageDigest md5Digest = DigestUtils.getMd5Digest();
System.out.println("MD5Hex with digest: " + DigestUtils.md5Hex(md5Digest.digest("12345".getBytes())));
System.out.println("MD5Hex: " + DigestUtils.md5Hex("12345"));
}
public final static String MD5(String s) {
char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
try {
byte[] btInput = s.getBytes();
// 獲得MD5摘要算法的 MessageDigest 對象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字節更新摘要
mdInst.update(btInput);
// 獲得密文
byte[] md = mdInst.digest();
// 把密文轉換成十六進制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
System.out.println();
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
The results as below:结果如下:
MessageDigest: 827CCB0EEA8A706C4C34A16891F84E7B
MD5Hex with digest: aad43635bbd353cef6ea6546093fa0c7
MD5Hex: 827ccb0eea8a706c4c34a16891f84e7b
If I have give md5Digest.digest() into DigestUtils.md5Hex, the result is different from MessageDigest.如果我将 md5Digest.digest() 输入 DigestUtils.md5Hex,结果与 MessageDigest 不同。 But if I just do md5Hex(), it will be the same.
但是如果我只做 md5Hex(),它会是一样的。 What's the different between this two way?
这两种方式有什么不同?
Thanks谢谢
When you are calling DigestUtils.md5Hex(md5Digest.digest("12345".getBytes())))
, you actually calculate the MD5 of the result of the previous MD5 calculation.当您调用
DigestUtils.md5Hex(md5Digest.digest("12345".getBytes())))
,实际上是在计算上一次 MD5 计算结果的 MD5。 Thus no wonder that double-MD5 differs from single MD5.因此,难怪双 MD5 与单 MD5 不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.