Sample Header Ad - 728x90

How to do HmacSHA256 using openSSL from terminal?

6 votes
4 answers
27412 views
I need to perform the following Java snippet using OpenSSL from the command line:
private byte[] hmacSha256(byte[] key, byte[] payload) throws GeneralSecurityException {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key, "HmacSHA256"));
    mac.update(payload);
    return mac.doFinal();
  }
These are the test values that are working with Java but not with OpenSSL:
KEY_BASE64="xtztqVgjD+5VHL4rVeKYm0USpDJTEy5Tjc9aK6I/oV0="
KEY_HEX="c6dceda958230fee551cbe2b55e2989b4512a43253132e538dcf5a2ba23fa15d"
PAYLOAD_BASE64="j9F8TrzCabcDoLdHUDaUuv6ea224xikwbPF1IW0OjkY="
DIGEST_HEX="c2ec711448a4f5bb851279eca0a628847254855966ad09de7e734b7df48e198a"
I already tried this answer but I got different results. It looked like this:
$ echo $PAYLOAD_BASE64 | base64 -d | openssl dgst -sha256 -hmac -hex -macopt hexkey:$KEY_HEX
(stdin)= 93d5555dbf95873441ccc63f9a4bc361e6f291f7b0a81db4edc35b8212b04dad
It does provide me an output in hex format, but the value doesn't match what I get when running that Java snippet with the same payload and key value. I could also use another command line tool, as long as it's widely available in most Linux default package managers lists.
Asked by Stefano (231 rep)
Sep 18, 2020, 12:08 PM
Last activity: Sep 19, 2023, 02:23 PM