Skip to content

Instantly share code, notes, and snippets.

@lesstif
Last active February 27, 2024 07:10
Show Gist options
  • Save lesstif/655f6b295a619306405621e02634a08d to your computer and use it in GitHub Desktop.
Save lesstif/655f6b295a619306405621e02634a08d to your computer and use it in GitHub Desktop.
HMAC SHA256 example java code
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class HMacTest {
public static final String ALGORITHM = "HmacSHA256";
public static String calculateHMac(String key, String data) throws Exception {
Mac sha256_HMAC = Mac.getInstance(ALGORITHM);
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), ALGORITHM);
sha256_HMAC.init(secret_key);
return byteArrayToHex(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}
public static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for(byte b: a)
sb.append(String.format("%02x", b));
return sb.toString();
}
public static void main(String [] args) throws Exception {
// see https://en.wikipedia.org/wiki/HMAC#Examples
// expected output:
// HMAC_SHA256("key", "The quick brown fox jumps over the lazy dog") = f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
System.out.println(calculateHMac("key", "The quick brown fox jumps over the lazy dog"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment