Java计算MD5哈希值
在 http://www.anyexample.com/programming/java/java_simple_class_to_compute_md5_hash.xml 给出了如何计算 String 的 MD5 哈希值的示例。这会产生 20 位十六进制字符串。根据 http://en.wikipedia.org/wiki/MD5 我期望一个 32 位数字十六进制字符串。例如,我在 如何生成 MD5 哈希?。
为什么我得到的东西看起来像 MD5 哈希值,但实际上不是?我无法想象我得到的所有字符串都必须用 12 个前导零填充。
编辑:一个代码示例
public static String MungPass(String pass) throws NoSuchAlgorithmException {
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] data = pass.getBytes();
m.update(data,0,data.length);
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032X", i);
}
In http://www.anyexample.com/programming/java/java_simple_class_to_compute_md5_hash.xml an example is given how to calculate an MD5 hash of String. This results in a 20 digit hex string. According to http://en.wikipedia.org/wiki/MD5 I would expect a 32 digit hex string. I get the same result for example using dac2009 response in How can I generate an MD5 hash?.
Why do I get something which looks like a MD5 hash but isn't? I cannot imagine that all the strings I get I have to pad with 12 leading zeros.
Edit: one code example
public static String MungPass(String pass) throws NoSuchAlgorithmException {
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] data = pass.getBytes();
m.update(data,0,data.length);
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032X", i);
}
Taken from http://snippets.dzone.com/posts/show/3686
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 org.apache.commons.codec.digest.DigestUtils 代替:
这将为您提供 32 个字符的字符串结果
use
org.apache.commons.codec.digest.DigestUtils
instead:this will give you 32 char string as a result
你一定是错过了什么。链接的代码很好。确保问题不在其他地方,与显示结果有关。可能性:
20
而不是0x20
,这是32
。You must be missing something. The linked code is just fine. Make sure the issue is nowhere else, related to displaying the result. Possibilities:
20
instead of0x20
, which is32
.您可以使用 DatatypeConverter.printHexBinary(digiest) 来获取由 32 个十六进制数字表示的 128 位哈希值。下面是生成 MD5 哈希 在Java中,
You can use DatatypeConverter.printHexBinary(digiest) to get the 128 bit hash represented by 32 hexadecimal numbers. Below is the complete code snippet to generate MD5 hash in Java,
我尝试了上面的示例,MungPass("java"),我得到了一个 32 位字符串,
93f725a07423fe1c889f448b33d21f46。既然你在跑步时得到了前 20 个正确的结果,我猜你只是在打印输出中遗漏了一些东西?
I tried your example above, MungPass("java") and I got a 32 digit string,
93f725a07423fe1c889f448b33d21f46. Since you got the 20 first of those correct when you ran, I'm guessing you are simply missing something in the printout?