Skip to Content
oxcrypto

Message authentication codes

Authenticate messages with a secret key.

Choose an algorithm, then call mac(key, data) for a tag, verify(key, data, tag) to check one, or new(key) for incremental input. verify raises oxcrypto.InvalidTag when the tag does not match. It compares tags with the digest crate's verify_slice, which is written to run in constant time; oxcrypto has not verified this independently. generate_key() returns a random key of the algorithm's nominal size from the operating system CSPRNG.

from oxcrypto.mac.hmac import HMAC

algorithm = HMAC.SHA256
key = algorithm.generate_key()
tag = algorithm.mac(key, b"message")
algorithm.verify(key, b"message", tag)

state = algorithm.new(key)
state.update(b"mess")
state.update(b"age")
state.verify(tag)

new(key) returns a MacState with update(data), copy(), finalize(), verify(tag) and reset(). finalize() and verify(tag) finish the state; using it afterwards raises ValueError until you call reset(), which restarts from the keyed initial state. States cannot be pickled. See Zeroization for what is wiped when a state is dropped.

Algorithms

  • HMAC RFC 2104 HMAC with named hash variants.
  • CMAC NIST SP 800-38B CMAC, including GOST R 34.13-2015 Kuznyechik and Magma.
  • PMAC Parallelizable MAC over 64-, 128- and 256-bit block ciphers.
  • CBC-MAC ISO/IEC 9797-1 MAC algorithm 1.
  • Retail MAC ISO/IEC 9797-1 MAC algorithm 3.

For Poly1305, GHASH and POLYVAL see universal hashes.

Zeroization

oxcrypto turns on the upstream crates' zeroize features, and only memory owned by Rust can be zeroized. The bytes you pass in as keys, the keys from generate_key() and the tags you get back are Python objects. Python does not wipe them, and the interpreter or your code may copy them. Compiler register spills and arithmetic temporaries inside cipher and field operations are also out of reach.

From reading their source, the upstream crates are written to wipe the state they keep (cipher key schedules, hash states, block buffers and MAC accumulators) when it is dropped. oxcrypto has not verified this independently, for example in the compiled code. Some upstream code also makes short-lived copies of key-derived values on the stack during setup or finalization and does not wipe them:

Algorithm(a) State the object keeps(b) Short-lived stack copies left unwiped
HMACinner and outer hash states, buffers: wipedthe K ⊕ ipad/K ⊕ opad block and a hashed long key in new
CMACkey schedule, chaining state: wipedthe subkeys L, K1 and K2 in finalize
PMACkey schedule, L cache, L⁻¹, offset, tag: wipedone leftover multiple of L in new
CBC-MAC, Retail MACkey schedules, chaining state: wipednone

The copies in column (b) are a known limitation.

On this page