I am using the following code to hash an incoming string, in expecting that same thing applied to the method multiple times will always get the same results. The scenario will be for password hashing and later verification. But it doesn’t seem to work – I got two different blobs for the same input string. Is there anything wrong or missing with my code?
public synchronized String encrypt(String token) {
try {
MessageDigest sha = MessageDigest.getInstance("SHA");
sha.reset();
sha.update(token.getBytes("UTF-8"));
byte[] raw = sha.digest();
System.out.println("raw = " + raw.toString());
String hash = Base64.encodeBase64(raw).toString();
return hash;
} catch (Exception e) {
}
return token;
}
You haven’t really given enough information, but I suspect you’re being distracted by this:
That’s going to print out something like
[B@30a4effewhich has nothing to do with the data in the byte array. You should print outhashinstead – which should be the same for all calls, if yourtokenis genuinely the same.(As noted by Dan, your method is inappropriately named: hashing isn’t encryption. Also, please don’t catch
Exceptionor just swallow exceptions like this. It seems pretty odd to just returntokenon failure, too.)EDIT: As noted, I’ve assumed that
Base64.encodeactually returns a String, which it may not. I’d recommend this base64 implementation which is public domain and has a sensible API – the encoding calls return a String, which is entirely appropriate. Of course, you then don’t need the explicittoString()call as well…