Hi I have written a class to create a hash for a String input but my Program sometimes give same hash for two different input.
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);
}
}
When my input to the function Hash() is "viud" the I am getting result as --> 0000000000000000000000[B@13e8c1c And when my input String is "Hello" then also I am getting result as --> 0000000000000000000000[B@13e8c1c
But this case is happening only few times on program execution. Every time I am running the Program,I am getting different hash generated for the same input value and also sometimes getting same hash value for two different inputs.
What happens exactly??
byte[] hashValue = t.Hash("viud");
String hashString = hashValue.toString();
toString on a byte[] will give you the memory (heap) address of the byte[]. This isn't what you want. You want
String hashString = new String(t.Hash("viud"));