6

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.

Stefano
  • 221

4 Answers4

6

I got this working. All I had to do is use openssl sha256 instead of openssl dgst -sha256.

Here's the full command:

$ echo $PAYLOAD_BASE64 | base64 -d | openssl sha256 -hex -mac HMAC -macopt hexkey:$KEY_HEX
(stdin)= c2ec711448a4f5bb851279eca0a628847254855966ad09de7e734b7df48e198a
Stefano
  • 221
4

If you installed NodeJs:

 echo "console.log(require('crypto').createHmac('sha256', 'nonbase64key').update('password').digest('hex'))" | node

it's equivalent in python is:

python3 -c 'import hashlib;import base64;import hmac;print(hmac.new(b"nonbase64key", "password".encode(), hashlib.sha256).hexdigest())'

And the equivalent pure shell command is:

echo -n "password" | openssl sha256 -hmac "nonbase64key"
Jeff Tian
  • 151
0

sample for macOS terminal are wrong.

my 2 cents if You are on iOS (or Mac OS...) tired of messing around I wrote it..

https://apps.apple.com/it/app/hmac-sha256generator/id6448465719?l=en

ingconti
  • 101
0

openssl sha256 -hex -mac HMAC -macopt key:<key here> file.txt