HMAC-SHA-2
The keyed message authentication codes HMAC-SHA-256, HMAC-SHA-512 and HMAC-SHA512-256 (truncated HMAC-SHA-512) are provided.
The crypto_auth
API provides a simplified interface for message authentication.
If required, a streaming API is available to process a message as a sequence of multiple chunks.
Single-part example
Multi-part example
Usage
HMAC-SHA-256
The crypto_auth_hmacsha256()
function authenticates a message in
whose length is inlen
using the secret key k
whose length is crypto_auth_hmacsha256_KEYBYTES
, and puts the authenticator into out
(crypto_auth_hmacsha256_BYTES
bytes).
The crypto_auth_hmacsha256_verify()
function verifies in constant time that h
is a correct authenticator for the message in
whose length is inlen
under a secret key k
(crypto_auth_hmacsha256_KEYBYTES
bytes).
It returns -1
if the verification fails, and 0
on success.
A multi-part (streaming) API can be used instead of crypto_auth_hmacsha256()
:
This alternative API supports a key of arbitrary length keylen
.
However, please note that in the HMAC construction, a key larger than the block size gets reduced to h(key)
.
This helper function introduced in libsodium 1.0.12 creates a random key k
.
It is equivalent to calling randombytes_buf()
but improves code clarity and can prevent misuse by ensuring that the provided key length is always be correct.
HMAC-SHA-512
Similarly to the crypto_auth_hmacsha256_*()
set of functions, the crypto_auth_hmacsha512_*()
set of functions implements HMAC-SHA512:
HMAC-SHA-512-256
HMAC-SHA-512-256 is implemented as HMAC-SHA-512 with the output truncated to 256 bits. This is slightly faster than HMAC-SHA-256. Note that this construction is not the same as HMAC-SHA-512/256, which is HMAC using the SHA-512/256 function.
Constants
crypto_auth_hmacsha256_BYTES
crypto_auth_hmacsha256_KEYBYTES
crypto_auth_hmacsha512_BYTES
crypto_auth_hmacsha512_KEYBYTES
crypto_auth_hmacsha512256_BYTES
crypto_auth_hmacsha512256_KEYBYTES
Data types
crypto_auth_hmacsha256_state
crypto_auth_hmacsha512_state
crypto_auth_hmacsha512256_state
Notes
The state must be initialized with
crypto_auth_hmacsha*_init()
before updating or finalizing it. Aftercrypto_auth_hmacsha*_final()
returns, the state should not be used any more, unless it is reinitialized usingcrypto_auth_hmacsha*_init()
.Arbitrary key lengths are supported using the multi-part interface.
crypto_auth_hmacsha256_*()
can be used to create AWS HMAC-SHA256 request signatures.Only use these functions for interoperability with 3rd party services. For everything else, you should probably use
crypto_auth()
/crypto_auth_verify()
orcrypto_generichash_*()
instead.
Last updated