在Java中尝试MD5哈希

维迪·阿加瓦尔

嗨,我编写了一个类来为String输入创建哈希,但是我的程序有时会为两个不同的输入给出相同的哈希。

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

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

到底会发生什么??

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章