views:

89

answers:

3

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();
}
A: 

Are you able to reproduce with some unit tests?

Matthieu BROUILLARD
+1  A: 

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.

rsp
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<messageDigest.length;i++) { hexString.append(Integer.toHexString(0xFF }`
David Soroko
A: 

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