[英]Java message digest [MD5] not producing expected hash
I am trying to generate an MD5 hex hash using the following code: 我正在尝试使用以下代码生成MD5十六进制哈希:
String password = "password";
MessageDigest digest = MessageDigest.getInstance("MD5");
ByteArrayInputStream bais = new ByteArrayInputStream(password.getBytes());
int size = 16;
byte[] bytes = new byte[size];
while ((bais.read(bytes, 0, size)) != -1)
{
digest.update(bytes);
}
byte[] hash = digest.digest();
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash)
{
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("MD5:/ " + sb.toString());
The output should be 5f4dcc3b5aa765d61d8327deb882cf99
(as checked with md5sum
), but I fail to see where the error is. 输出应该是
5f4dcc3b5aa765d61d8327deb882cf99
(与md5sum
检查),但是我看不到错误在哪里。 What am I doing wrong? 我究竟做错了什么?
I don't know what is wrong with yours, but this should work: 我不知道您的问题是什么,但这应该可以解决:
byte[] array = MessageDigest.getInstance("MD5").digest("password".getBytes("UTF-8"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
}
System.out.println(sb.toString());
You should update only part of read bytes: 您应该只更新部分读取的字节:
int len;
byte[] bytes = new byte[size];
while ((len = bais.read(bytes, 0, size)) != -1)
{
digest.update(bytes, 0, len);
}
You put always a full bytes
array (16 bytes) into the digest, even if the password was shorter. 即使密码较短,也始终将完整的
bytes
数组(16字节)放入摘要中。
Btw. 顺便说一句。 the whole construction with the stream is not necessary, you can simply do:
不需要使用流进行整体构建,只需执行以下操作:
byte[] hash = digest.digest(password.getBytes("UTF-8"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.