Reputation: 17
I have written a code to generate a MD5 but unfortunately its generating a new MD5 every time for the same string. Can anyone please help.
Code is like below :
public static byte[] getHash(String[] constants)
{
MessageDigest md= MessageDigest.getInstance("MD5");
StringBuilder toBeHashed=new StringBuidler();
for(String c: constants)
{
toBeHashed.append(c);
}
return md.digest(toBeHashed.toString().getBytes());
}
Driver code :
byte[] hash=MyClass.getHash(new String[] {"01L488213P9579","2021-31-31"});
Can anyone please help and let me know if the code I wrote is correct or not? Is it because of the new String array, I am passing every time ?
Upvotes: 1
Views: 116
Reputation: 44980
The problem is here, when you say:
printing hash in my driver code, its coming like B@12.. something , new everytime
You are printing the array object which uses toString()
method which for arrays shows the object hash code. It is unique for every array object so each time you get a new value.
You have to print the array content e.g. using java.util.Arrays
:
System.out.println(java.util.Arrays.toString(hash));
Upvotes: 4