Generating HMAC Signatures on the Command Line with OpenSSL

Proving authenticity of a message is important, even over transport methods such as HTTPS, as we may not be able to require full end-to-end encryption. One such method of producing a signature is using HMAC with a shared secret.

For instance, let us say that we want to use SHA256 as the hashing algorithm.

If using Java, we could write code similar to the below, leveraging the commons-codec project:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
// ...
String digest =
    new String(
        Base64.encodeBase64String(
            new HmacUtils(HmacAlgorithms.HMAC_SHA_256, "secret-key-here")
                .hmac("value-to-digest")));
// G73zFnFYggHRpmwuRFPgch6ctqEfyhZu33j5PQWYm+4=

However, this doesn't help when we want to script this from the command-line, and isn't as portable.

To do this we can utilise openssl:

$ echo -n "value-to-digest" | openssl dgst -sha256 -hmac "secret-key-here" -binary | openssl enc -base64 -A
# G73zFnFYggHRpmwuRFPgch6ctqEfyhZu33j5PQWYm+4=

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #command-line #openssl #hmac #java.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.