2.3. Hash Functions and HMACs
We provide a single hash function implemented on top of SHA-512. We also provide an implementation for hash-based message authentication codes (HMACs).
2.3.1. Functions
- crypto.Hash(data: bytes) bytes
Computes a hash of
data
using SHA-512, a cryptographically secure hash function; the returned hash has a length of 64 bytes.- Returns:
The resulting hash of
data
as abytes
object of 64 bytes in length- Return type:
bytes
Warning
If you want a “keyed hash function” (i.e. akin to \(\textsf{hash}(k~||~m)\), where \(k\) is a secret key), you should use
crypto.HMAC
instead of callingcrypto.Hash
on the concatenation ofkey
anddata
. Using a naive construction that involves simply passing the concatenation of \(k\) and \(m\) tocrypto.Hash
can allow the adversary to recover \(k\) via a length extension attack.
- crypto.HMAC(key: bytes, data: bytes) bytes
Computes a SHA-512 hash-based message authentication code (HMAC) of
data
usingkey
; the returned HMAC has a length of 64 bytes. Returns an error ifkey
is not 128 bits (16 bytes).- Parameters:
key (bytes) – The private key
data (bytes) – The bytes to compute an HMAC over
- Returns:
The resulting HMAC as a
bytes
object of 64 bytes in length- Return type:
bytes
- Raises:
ValueError – if
key
is not 128 bits (16 bytes)
- crypto.HMACEqual(a: bytes, b: bytes) bool
Compares whether two HMACs (
a
andb
) are the same in a constant-time manner.- Parameters:
a (bytes) – An HMAC
b (bytes) – An HMAC
- Returns:
True
ifa
is equal tob
; otherwise,False
- Return type:
bool
Note
crypto.HMACEqual
is the cryptographically secure way to compare HMACs for equality. Performing byte equality checks naively (i.e. via the linear-time equality operator==
) may leave your implementation vulnerable to timing attacks that allow the adversary to forge valid HMACs even without knowledge of the private key.