6

I'm trying to use openssl to create a cryptographic hash of a file using HMAC-SHA-256. I'm confused as to why I'm seeing a 'no such file or directory' error on the output.

The key I'm using is in a file called mykey.txt.

This is my command:

openssl dgst -sha256 -hmac -hex hexkey:$(cat mykey.txt) -out hmac.txt /bin/ps

And the output

enter image description here

ilkkachu
  • 138,973

3 Answers3

11

-hmac takes the key as an argument (see manual), so your command asks for an HMAC using the key -hex. hexkey:... is taken as a filename, since it doesn't start with a dash, and openssl doesn't take options after filenames, so the following -out is also a filename.

To get the HMAC with a key given as a hex string, you'll need to use -mac hmac and -macopt hexkey:<key>. Note that using -hmac <key> and -mac hmac together doesn't work, and -macopt requires -mac hmac.

Test:

openssl dgst -sha256 -hmac abc <<< "message"
openssl dgst -sha256 -hmac abc -macopt hexkey:12345678 <<< "message"
openssl dgst -sha256 -mac hmac -macopt hexkey:616263 <<< "message"
perl -MDigest::HMAC=hmac_hex -MDigest::SHA=sha256 \
    -le 'print(hmac_hex("message\n", "abc", \&sha256))'

All give the hash 99592e56fcde028fb41882668b0cbfa0119116f9cf111d285f5cedb000cfc45a which agrees with a random online HMAC calculator for message message\n, key abc or 616263 in hex. (Note the newline at the end of message here.)

So, it seems you'd probably want

openssl dgst -sha256 -mac hmac -macopt hexkey:$(cat mykey.txt) -out hmac.txt /bin/ps

Since we're talking about cryptography, which is hard; and OpenSSL, which doesn't always have the most easy-to-use interfaces, I would suggest also verifying everything yourself, at least twice, instead of taking my word for it.

ilkkachu
  • 138,973
3

openssl dgst -sha256 -hmac -hex -macopt hexkey:$(cat mykey.txt) -out hmac.txt /bin/ps

  • At least on the OpenSSL (1.1.0f) on my system, that's exactly the same as if -macopt hexkey... was left out. That is, it calculates the HMAC using the key -hex, instead of using the parameter to -macopt. – ilkkachu May 20 '18 at 18:49
  • Well, the question was "why am I seeing the error" - broken command arguments flow is often an irritating showstopper for further work. But sure, you're answer covers this much wider. – Tomasz Pala May 20 '18 at 19:51
  • If all we care about is removing the immediate error message, then the command could have been reduced to just openssl dgst -sha256 -hmac -hex -out hmac.txt /bin/ps (or even further). That's probably not very useful, but at least it doesn't throw errors. – ilkkachu May 20 '18 at 20:31
  • It's not about removing the error message by stepping back, but showing how to pass the hexkey argument itself. – Tomasz Pala May 20 '18 at 20:44
0

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