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
datausing SHA-512, a cryptographically secure hash function; the returned hash has a length of 64 bytes.- Returns:
The resulting hash of
dataas abytesobject 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.HMACinstead of callingcrypto.Hashon the concatenation ofkeyanddata. Using a naive construction that involves simply passing the concatenation of \(k\) and \(m\) tocrypto.Hashcan 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
datausingkey; the returned HMAC has a length of 64 bytes. Returns an error ifkeyis 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
bytesobject of 64 bytes in length- Return type:
bytes
- Raises:
ValueError – if
keyis not 128 bits (16 bytes)
- crypto.HMACEqual(a: bytes, b: bytes) bool
Compares whether two HMACs (
aandb) are the same in a constant-time manner.- Parameters:
a (bytes) – An HMAC
b (bytes) – An HMAC
- Returns:
Trueifais equal tob; otherwise,False- Return type:
bool
Note
crypto.HMACEqualis 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.