【问题标题】:Trying MD5 Hash in java [duplicate]在java中尝试MD5 Hash [重复]
【发布时间】:2019-11-01 21:24:59
【问题描述】:

您好,我编写了一个类来为字符串输入创建哈希,但我的程序有时会为两个不同的输入提供相同的哈希。

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class Test {

public byte[] Hash(String input) throws NoSuchAlgorithmException
{
    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    byte b[] = messageDigest.digest(input.getBytes());
    return b;
}

public static void main(String args[]) throws NoSuchAlgorithmException
{
   Test t = new Test();
   byte[] hashValue = t.Hash("viud");
   String hashString = hashValue.toString();
   while(hashString.length()<32)
   {
       hashString = "0" + hashString;
   }
   System.out.println(hashString);
}

}

当我对函数 Hash() 的输入是 "viud" 时,我得到的结果为 --> 0000000000000000000000[B@13e8c1c 当我的输入字符串是 "Hello" 时,我得到的结果也为 --> 0000000000000000000000[B@13e8c1c

但是这种情况在程序执行时只发生过几次。 每次运行程序时,我都会为相同的输入值生成不同的哈希值,有时还会为两个不同的输入值生成相同的哈希值。

究竟发生了什么??

【问题讨论】:

    标签: java hash message-digest


    【解决方案1】:
       byte[] hashValue = t.Hash("viud");
       String hashString = hashValue.toString();
    
    byte[] 上的

    toString 将为您提供 byte[] 的内存(堆)地址。这不是你想要的。你想要的

    String hashString = new String(t.Hash("viud"));
    

    【讨论】:

    • 使用 String hashString = new String(t.Hash("viud")) 会给我每个输入的唯一哈希? @ControlAltDel
    • @VidhiAgarwal 不,哈希不能是唯一的,因为您将无限数量的输入映射到 16 个字节的序列(对于 MD-5)。
    • @VidhiAgarwal 否。没有哈希码算法会产生唯一的哈希。
    • 我尝试了你的解决方案,但现在输出为 -- 0000000000000000]A@*¼K*v¹q?'Å' @ControlAltDel
    • @VidhiAgarwal 为此,您应该使用所谓的 salt。你可以阅读this article。如果你真的想这样做,你可能不应该使用 MD5..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多