Quick tip: SHA1 or MD5 checksum strings in Java

In a recent project (OK, I was processing FOAF data), I needed to be able to generate the hex-encoded string of a SHA1 checksum. The built-in Java security classes can do the heavy-lifting, of generating the checksum itself, but they deliver the resulting checksum as a byte-array. I needed the string encoding of that array. There are various code-snippets around on the web to do that, by iterating over the byte array and incrementally building up the string in a buffer, but they look low-level and inelegant. The following is much neater (written for SHA1, but the method works for the other digest formats):

public String getEncodedSha1Sum( String key ) {
    try {
        MessageDigest md = MessageDigest.getInstance( "SHA1" );
        md.update( key.getBytes() );
        return new BigInteger( 1, md.digest() ).toString(16);
    }
    catch (NoSuchAlgorithmException e) {
        // handle error case to taste
    }
}

Kudos to Brian Gianforcaro on StackOverflow for the tip

 newer · index · older