开发者

MessageDigest digest() method

Shouldn't the digest() method in MessageDigest always give the same hash value for the same input?

I tried this a开发者_如何学JAVAnd I am getting different set of hashvalues for the same input everytime

md5 = MessageDigest.getInstance("MD5");
System.out.println(md5.digest("stringtodigest".getBytes()));
System.out.println(md5.digest("stringtodigest".getBytes())); 
System.out.println(md5.digest("stringtodigest".getBytes()));

Update: Changed the param to digest() method


You're seeing the results of calling byte[].toString() - which isn't showing you the actual hash of the data. You're basically getting a string which shows that you've called toString on a byte array (that's the [B part) and then the hash returned by Object.hashCode() (that's the hex value after the @). That hash code doesn't take the data in the array into account.

Try

System.out.println(Arrays.toString(md5.digest(byteArrayToDigest)));

to see the actual data.

EDIT: Quick note about creating an MD5 digest from string data - you should always use the same encoding, explicitly, when hashing. For example:

byte[] hash = md5.digest(text.getBytes("UTF-8"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜