HMAC SHA512 in Java

When doing some research on authentication tokens I came across the post Don’t Hash Secrets and learn’t of a few new things, one of which was HMAC: Hash-based message authentication code.

I use Google Guava for some utility functions, but it doesn’t have a built in HMAC function. The code below still uses Guava for BaseEncoding.

private static final String DEFAULT_ENCODING = "UTF-8";
private static final String HMAC_SHA512 = "HmacSHA512";
 
public static byte[] hmacSha512(String value, String key){
    try {
        SecretKeySpec keySpec = new SecretKeySpec(
                key.getBytes(DEFAULT_ENCODING),
                HMAC_SHA512);
 
        Mac mac = Mac.getInstance(HMAC_SHA512);
        mac.init(keySpec);
        return mac.doFinal(value.getBytes(DEFAULT_ENCODING));
 
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
public static String asHex(byte[] bytes){
    return BaseEncoding.base16().lowerCase().encode(bytes);
}

I used the HMAC Generator / Tester Tool to generate test data.

This entry was posted in Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *