Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is MessageDigest returning different answers for the same string?

Tags:

java

I am trying to get a hash value for a string using MessageDigest in Java, but the value is different every time. When I run the program twice it will again have completely different answers.

        MessageDigest md = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException nsae) {
        }

        md.update("string".getBytes());
        byte[] digest = md.digest();
        System.out.println(digest);

        md.reset();

        md.update("string".getBytes());
        byte[] digest2 = md.digest();
        System.out.println(digest2);
like image 490
user1183661 Avatar asked Feb 22 '12 17:02

user1183661


1 Answers

You are outputting the byte[] object, not the byte array contents. Use

System.out.println(Arrays.toString(digest1));
....
System.out.println(Arrays.toString(digest2));
like image 158
Alexander Pavlov Avatar answered Oct 05 '22 01:10

Alexander Pavlov