gpt4 book ai didi

java - 在java中尝试MD5哈希

转载 作者:行者123 更新时间:2023-12-02 09:21:35 24 4
gpt4 key购买 nike

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

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”时,我得到的结果为 --> 00000000000000000000000[B@13e8c1c当我的输入字符串是 "Hello" 时,我得到的结果也为 --> 0000000000000000000000[B@13e8c1c

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

究竟发生了什么?

最佳答案

   byte[] hashValue = t.Hash("viud");
String hashString = hashValue.toString();
byte[] 上的

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

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

关于java - 在java中尝试MD5哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58659955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com