Java Utililty Methods HMAC

List of utility methods to do HMAC

Description

The list of methods to do HMAC are organized into topic(s).

Method

StringhmacSha(String crypto, String key, String value)
General hmac method - can pass in any crypto string recognised by Mac.getInstance .
try {
    byte[] keyBytes = hexStr2Bytes(key);
    Mac hmac;
    hmac = Mac.getInstance(crypto);
    SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
    hmac.init(macKey);
    return bytesToHex(hmac.doFinal(value.getBytes()));
} catch (GeneralSecurityException gse) {
...
byte[]hmacSha1(byte[] data, byte[] key)
Do HMAC-SHA1.
SecretKey skey = new SecretKeySpec(key, "HmacSHA1");
Mac mac;
try {
    mac = Mac.getInstance("HmacSHA1");
    mac.init(skey);
} catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
mac.update(data);
return mac.doFinal();
byte[]hmacSha1(byte[] key_bytes, byte[] text_bytes)
hmac Sha
Mac hmacSha1;
try {
    hmacSha1 = Mac.getInstance("HmacSHA1");
} catch (NoSuchAlgorithmException nsae) {
    hmacSha1 = Mac.getInstance("HMAC-SHA-1");
SecretKeySpec macKey = new SecretKeySpec(key_bytes, "RAW");
hmacSha1.init(macKey);
...
byte[]hmacSha1(byte[] secret, byte[] data)
hmac Sha
String algo = "HmacSHA1";
SecretKey secretKey = new SecretKeySpec(secret, algo);
Mac m = Mac.getInstance(algo);
m.init(secretKey);
return m.doFinal(data);
byte[]hmacSha1(SecretKey key, byte[] data)
hmac Sha
Mac m = Mac.getInstance(HmacSHA1);
m.init(key);
m.update(data);
byte[] mac = m.doFinal();
return mac;
byte[]hmacSha1(SecretKeySpec signingKey, byte[]... data)
hmac Sha
Mac mac = buildHmacSha1(signingKey);
return hmacSha1(mac, data);
StringhmacSha1(String data, String key)
hmac Sha
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
Mac mac = null;
try {
    mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
    throw new RuntimeException(e);
byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(rawHmac);
byte[]hmacSha1(String input, byte[] keyBytes)
Hmac sha1.
try {
    SecretKey secretKey = new SecretKeySpec(keyBytes, HMACSHA1);
    Mac mac = Mac.getInstance(HMACSHA1);
    mac.init(secretKey);
    return mac.doFinal(input.getBytes());
} catch (GeneralSecurityException e) {
    throw new IllegalStateException("Security exception", e);
byte[]hmacSha1(String input, byte[] keyBytes)
hmac Sha
try {
    SecretKey secretKey = new SecretKeySpec(keyBytes, HMACSHA1);
    Mac mac = Mac.getInstance(HMACSHA1);
    mac.init(secretKey);
    return mac.doFinal(input.getBytes());
} catch (GeneralSecurityException e) {
    throw convertRuntimeException(e);
byte[]hmacSHA256(byte[] secret, byte[] data)
hmac SHA
Mac sha256HMAC = Mac.getInstance(HMAC_SHA_256);
SecretKeySpec secret_key = new SecretKeySpec(secret, HMAC_SHA_256);
sha256HMAC.init(secret_key);
return sha256HMAC.doFinal(data);