1

I've got this function for encrypting passwords in Java, but somehow when I call MessageDigest, it returns a different result every time even though I call it with the same password. I wonder if I am initializing it wrong somehow.

public String encrypt (String password) {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.reset();     
    md.update(password.getBytes(Charset.forName("utf-8")),0,password.length());
    String res = md.digest().toString();
}
Adam Lear
  • 38,111
  • 12
  • 81
  • 101
user344146
  • 93
  • 6

3 Answers3

3

This simple code produces three different results :

    MessageDigest digest = MessageDigest.getInstance("MD5");
    System.out.println("test1 ");
    System.out.println(digest.digest("test".getBytes("UTF-8")));

    Thread.sleep(10000);        
    System.out.println("test2 ");
    System.out.println(digest.digest("test".getBytes("UTF-8")));

    Thread.sleep(10000);
    System.out.println("test3 ");
    System.out.println(digest.digest("test".getBytes("UTF-8")));
Meex
  • 31
  • 2
  • 1
    same behaviour with a SHA-1 digest, very ackward... it should be constant, shouldn't it ? – Meex Aug 22 '11 at 13:31
  • The `digest()` function returns a `byte[]`. When run three times, it returns three different byte array references, but they do contain the same digest bytes. You can verify that by printing out the hex strings of the byte arrays instead of the array reference itself. – Rob Meeuwisse Oct 25 '15 at 17:37
2

The .toString() method on the byte[] that is the return value of .digest() just gives you the representation of the array, not of its contents.

See this answer on how to convert your byte array to a hex string.

Another approach is using Arrays.toString(byte[]) although that probably does not give you the format you want.

Community
  • 1
  • 1
rsp
  • 23,135
  • 6
  • 55
  • 69
  • 1
    Exactly `md.digest().toString` has nothing to do with the content of the byte array. Just it's object representation. an alternative `StringBuffer hexString = new StringBuffer(); for (int i=0;i – David Soroko May 18 '10 at 15:20
1

You could change the method signature:

public byte[] encrypt (String password) {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    md.reset();
    md.update(password.getBytes(Charset.forName("utf-8")), 0, password.length());
    return md.digest();
}

... and use Arrays.equals(byte[], byte[]) to compare digests.

hudolejev
  • 5,846
  • 4
  • 22
  • 28