hmac_functional#

Compute a keyed HMAC digest of the data arguments in one call.

Shared dispatcher for every hmac_sha* one-shot: 21 Perl-level names (7 algorithms × 3 encodings) all land here. The name selects both the underlying SHA algorithm and the output encoding:

  • hmac_sha1, hmac_sha256, … return the raw binary MAC.

  • hmac_sha1_hex, hmac_sha256_hex, … return the lowercase hex MAC.

  • hmac_sha1_base64, hmac_sha256_base64, … return the unpadded Base64 MAC.

Argument shape matches upstream: the last argument is the key, every preceding argument is message data (concatenated byte-wise). With a single argument the key is that argument and the message is empty. With no arguments both key and message are empty.

Synopsis#

use Digest::SHA qw(hmac_sha256_hex hmac_sha1_base64);
my $tag = hmac_sha256_hex($message, $key);
my $b64 = hmac_sha1_base64(@chunks, $key);

What you get back#

A plain scalar. The raw-binary form has the fixed length of the chosen algorithm’s digest (20 bytes for SHA-1, 32 for SHA-256, 64 for SHA-512, and so on). The _hex form is twice that length; the _base64 form is the unpadded Base64 encoding.

Examples#

use Digest::SHA qw(hmac_sha256_hex);
my $mac = hmac_sha256_hex("Hi There", "\x0b" x 20);

## b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7
use Digest::SHA qw(hmac_sha1_hex);

## Concatenated message: "Hello, " + "world!"

my $mac = hmac_sha1_hex("Hello, ", "world!", $shared_secret);
use Digest::SHA qw(hmac_sha512_base64);
my $cookie_tag = hmac_sha512_base64($cookie_body, $server_secret);
use Digest::SHA qw(hmac_sha256_hex);
my $tag = hmac_sha256_hex($key);   # one arg: key only, empty message

Edge cases#

  • Single-argument calls treat the sole argument as the key and hash an empty message. This matches upstream behaviour and is rarely what you want — pass message and key explicitly.

  • Keys longer than the algorithm’s block size are hashed down to digest size before use (standard HMAC key reduction).

  • Wide characters in either key or data croak with Wide character in subroutine entry.

Differences from upstream#

Fully compatible with upstream Digest::SHA 6.04.

See also#

  • sha256_hex — unkeyed one-shot digest for integrity-only needs.

  • Digest::SHA->new(256)->add(...)->hmac_hex($key) — no OO HMAC exists; if you need incremental HMAC use Digest::HMAC_SHA1 or feed a keyed construction manually.

  • hmac_sha1_hex — SHA-1 variant; prefer SHA-256 or larger for new code.