Re: Getting a nice string representation of a MessageDigest
Tom Anderson wrote:
On Thu, 2 Oct 2008, zerg wrote:
MessageDigest.toString produces an awkward and bulky mess with square
brackets and other awkward symbols inside.
I'd like to know of a simple way to get a nicer, preferably purely
alphanumeric string representation from a MessageDigest, but one which
doesn't lose information (i.e. if two MessageDigests are different,
their representations will be different).
Is the best way to get the byte array out and then render it in hex or
similarly?
I don't think there's a bytes-to-hex converter in the standard library,
but it's not exactly aerospace engineering:
private static final String HEX = "0123456789abcdef" ;
static String toHexString(byte[] buf) {
char[] chars = new char[buf.length * 2] ;
for (int i = 0 ; i < buf.length ; ++i) {
chars[2 * i] = HEX.charAt((buf[i] >> 4) & 0xf) ;
chars[(2 * i) + 1] = HEX.charAt(buf[i] & 0xf) ;
}
return new String(chars) ;
}
static String toHexString(MessageDigest hash) {
return toHexString(hash.digest()) ;
}
Pretty close to what I came up with:
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String getHashString (byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length*2);
for (byte b : bytes) {
sb.append(HEX_DIGITS[b >> 4]);
sb.append(HEX_DIGITS[b & 0xf]);
}
return sb.toString();
}
Output resembles 09f911029d74e35bd84156c5635688c0 (example is for a
128-bit byte array -- 16 bytes).