簡體   English   中英

Java消息摘要[MD5]未產生預期的哈希

[英]Java message digest [MD5] not producing expected hash

我正在嘗試使用以下代碼生成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());

輸出應該是5f4dcc3b5aa765d61d8327deb882cf99 (與md5sum檢查),但是我看不到錯誤在哪里。 我究竟做錯了什么?

我不知道您的問題是什么,但這應該可以解決:

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());

您應該只更新部分讀取的字節:

    int len;
    byte[] bytes = new byte[size];
    while ((len = bais.read(bytes, 0, size)) != -1)
    {
        digest.update(bytes, 0, len);
    }

即使密碼較短,也始終將完整的bytes數組(16字節)放入摘要中。

順便說一句。 不需要使用流進行整體構建,只需執行以下操作:

byte[] hash = digest.digest(password.getBytes("UTF-8"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM