I'm storing the user password on the db as a sha1 hash.
Unfortunately I'm getting strange answers.
I'm storing the string as this:
MessageDigest cript = MessageDigest.getInstance("SHA-1");
cript.reset();
cript.update(userPass.getBytes("utf8"));
this.password = new String(cript.digest());
I wanted something like this -->
aff --> "0c05aa56405c447e6678b7f3127febde5c3a9238"
rather than
aff --> �V@\D~fx����:�8
If you don't want to add any extra dependencies to your project, you could also use
you can use this code too(from crackstation.net):
private static String toHex(byte[] array) { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if(paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex; else return hex; }
You need to hex encode the result first.
MessageDigest
returns a "raw" hash, rather than a human readable one.Edit:
@thejh provided a link to code which should work. Personally, I'd suggest using either Bouncycastle or Apache Commons Codec to do the job. Bouncycastle would be good if you want to do any other crypto-related operations.
echo -n "aff" | sha1sum produce the correct output (echo inserts a newline by default)
To use UTF-8, do this:
And to get a Base64 String from the digest, you can do something like this:Since
MessageDigest.digest()
returns a byte array, you can convert it to String using Apache's Hex Encoding (simpler).E.g.