crypto#
hashes, MACs, KDFs, Argon2id, AEAD, X25519, Ed25519, sealed boxes (no randomness inside) -- crate root lib/crypto/lib.rs
crypto -- the primitives BackupCraft (and anything else) builds on, in plain Rust
sha2 Sha224 / Sha256 / Sha384 / Sha512, sha224 .. sha512(data) (FIPS 180-4)
sha3 Sha3_224 .. Sha3_512, sha3_224 .. sha3_512(data); Shake128 / Shake256 with any
output length, shake128 / shake256(data, out) (FIPS 202)
hmac Hmac<H>, hmac_sha256 / hmac_sha512, hkdf_sha256 / hkdf_sha512,
pbkdf2_sha256 (import of foreign key files only) (RFC 2104/5869/8018)
blake2b Blake2b (keyed, 1..64 byte digests) (RFC 7693)
blake3 Blake3 (hash, keyed_hash, derive_key, any output length)
argon2 argon2id(password, salt, params, out), PHC strings hash / verify (RFC 9106)
chacha ChaCha20 (IETF), HChaCha20, XChaCha20 (RFC 8439)
poly1305 Poly1305 one-time authenticator (RFC 8439)
aead ChaCha20-Poly1305 and XChaCha20-Poly1305 seal / open (RFC 8439)
x25519 Diffie-Hellman over Curve25519 (RFC 7748)
ed25519 signatures, strict verification (RFC 8032)
ed448 Ed448 signatures (SHAKE256, contexts), strict verification (RFC 8032 5.2)
sealbox anonymous public-key encryption: X25519 + HKDF-SHA256 + XChaCha20-Poly1305
aes, gcm AES-128/192/256 (bitsliced, constant time; both directions), AES-GCM seal / open
(FIPS 197, SP 800-38D)
bn big integers modulo odd numbers (public values: variable time; pow_ct for a
secret exponent)
rsa RSA PKCS #1 v1.5 and PSS verification (MGF1 of the same hash) (RFC 8017)
ecdsa ECDSA on P-256 / P-384: verification; signing in constant time with
deterministic nonces (RFC 6979), hedged by optional random bytes; keys; r || s
(IEEE P1363) and DER (FIPS 186-5, RFC 6979)
p256 Diffie-Hellman on P-256 in constant time (complete formulas) (SEC 1)
p384 Diffie-Hellman on P-384 in constant time (complete formulas) (SEC 1)
b64 Base64 (standard and URL alphabet, with or without padding)
ct_eq / zeroize / hex
sha1 Sha1, sha1(data); with hmac_sha1, pbkdf2 (any Hash) and pbkdf2_sha1 in hmac:
only for protocols defined with SHA-1 (WPA2-Personal) (FIPS 180-4)
keywrap aes_wrap / aes_unwrap: the AES key wrap (RFC 3394)
cmac cmac_aes: AES-CMAC (RFC 4493)
md5 Md5, md5(data), md5_parts(parts); with hmac_md5 in hmac: only for protocols
defined with MD5 (RADIUS); broken for collisions (RFC 1321, 2104)
rsa also PrivateKey: generate from the caller's bytes, PKCS #1 v1.5 and PSS signing
(RFC 8017)
eappwd the sums of EAP-PWD on P-256: pwe, commit, shared, confirm, keys (RFC 5931)
mlkem ML-KEM-512 / 768 / 1024: keygen from a 64-byte seed, encaps, decaps with implicit
rejection, in constant time (FIPS 203)
No randomness here: callers pass random bytes in (plat::fill_random on Windows, Linux, Apple
and Android; in the browser the page's crypto.getRandomValues), so everything is
deterministic and testable. Secret-dependent work avoids branches and table lookups
(field arithmetic with 51-bit limbs, masked conditional swaps and selects); every mask made
from secret data passes ct_mask, so the optimizer cannot turn a select back into a branch.
crypto crate root#
trait Hash: Clonea hash function for Hmac / HKDF / PBKDF2const BLOCK: usizeblock size in bytes (at most 168)const OUT: usizedigest size in bytes (at most 64)fn new() -> Selffn update(&mut self, data: &[u8])fn finish_into(self, out: &mut [u8])the digest into out[..OUT]
enum HashAlgthe hash functions of signaturesSha256Sha384Sha512Sha224Sha3_224Sha3_256Sha3_384Sha3_512
impl HashAlg
fn len(self) -> usizefn digest(self, data: &[u8]) -> Vec<u8>fn hmac(self, key: &[u8], data: &[u8]) -> Vec<u8>HMAC with this hash (RFC 2104): the full tagfn ct_eq(a: &[u8], b: &[u8]) -> boolequality of two byte strings in time that depends only on their lengthsfn zeroize(buf: &mut [u8])overwrite a secret (the write is kept even though nothing reads the buffer afterwards)fn hex(data: &[u8]) -> Stringlower-case hex (without a table: keys are printed this way too)fn unhex(s: &str) -> Option<Vec<u8>>the bytes of a hex string (upper or lower case; None on odd length or other characters). Every character is looked at before the answer, without a branch on it
crypto/aead.rs#
Source: lib/crypto/aead.rs
aead -- ChaCha20-Poly1305 (RFC 8439) and XChaCha20-Poly1305 (192-bit nonces: random nonces
are safe)
seal_in_place(key, nonce, aad, buf) -> tag open_in_place(.., buf, &tag) -> ok
seal(key, nonce, aad, plain) -> ciphertext ‖ tag open(.., sealed) -> Some(plain)
(x_* : the same with a 24-byte nonce)
KEY_LEN: usize = 32
NONCE_LEN: usize = 12
XNONCE_LEN: usize = 24
TAG_LEN: usize = 16
fn seal_in_place(key: &[u8; 32], nonce: &[u8; 12], aad: &[u8], buf: &mut [u8]) -> [u8; 16]encrypt buf in place -> the tagfn open_in_place(key: &[u8; 32], nonce: &[u8; 12], aad: &[u8], buf: &mut [u8], t: &[u8; 16]) -> boolcheck the tag and decrypt buf in place -> false (buf unchanged) on a wrong tagfn seal(key: &[u8; 32], nonce: &[u8; 12], aad: &[u8], plain: &[u8]) -> Vec<u8>ciphertext ‖ tagfn open(key: &[u8; 32], nonce: &[u8; 12], aad: &[u8], sealed: &[u8]) -> Option<Vec<u8>>the plaintext of ciphertext ‖ tag (None: too short or forged)fn x_seal_in_place(key: &[u8; 32], nonce: &[u8; 24], aad: &[u8], buf: &mut [u8]) -> [u8; 16]XChaCha20-Poly1305: encrypt buf in place -> the tagfn x_open_in_place(key: &[u8; 32], nonce: &[u8; 24], aad: &[u8], buf: &mut [u8], t: &[u8; 16]) -> boolXChaCha20-Poly1305: check and decrypt in placefn x_seal(key: &[u8; 32], nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec<u8>XChaCha20-Poly1305: ciphertext ‖ tagfn x_open(key: &[u8; 32], nonce: &[u8; 24], aad: &[u8], sealed: &[u8]) -> Option<Vec<u8>>XChaCha20-Poly1305: the plaintext of ciphertext ‖ tag
crypto/aes.rs#
Source: lib/crypto/aes.rs
aes -- AES-128 / AES-192 / AES-256 (FIPS 197) in constant time
Aes::new(key) (16, 24 or 32 bytes) aes.encrypt4(&mut [[u8; 16]; 4]) aes.encrypt(&mut block)
aes.decrypt4(&mut [[u8; 16]; 4]) aes.decrypt(&mut block)
Bitsliced: four blocks at a time in eight 64-bit words, word i holding bit i of all 64 bytes
(bit position = row * 16 + column * 4 + block). SubBytes inverts in GF(2^8) with
multiplications on those bit planes (x^254 by four multiplications and seven squarings),
then applies the affine map; ShiftRows rotates inside the 16-bit row fields, MixColumns
rotates whole rows. No table lookups, no branches on data or key: what GCM needs for
TLS. The inverse cipher (CBC of the Secret Service, plat::secret) undoes the affine map
before the same inversion; InvMixColumns is MixColumns after a_r ^= 4 (a_r ^ a_(r+2)).
struct Aes
impl Aes
fn new(key: &[u8]) -> Option<Aes>a 16-byte (AES-128), 24-byte (AES-192) or 32-byte (AES-256) keyfn encrypt4(&self, blocks: &mut [[u8; 16]; 4])encrypt four blocks in placefn encrypt(&self, block: &mut [u8; 16])encrypt one block in placefn decrypt4(&self, blocks: &mut [[u8; 16]; 4])decrypt four blocks in placefn decrypt(&self, block: &mut [u8; 16])decrypt one block in place
crypto/argon2.rs#
Source: lib/crypto/argon2.rs
argon2 -- Argon2id (RFC 9106, version 0x13) and PHC strings
argon2id(password, salt, &Params, out) raw tag (secret / associated data empty)
argon2id_ex(password, salt, secret, ad, &Params, out)
hash(password, salt, &Params) -> "$argon2id$v=19$m=..,t=..,p=..$salt$hash"
verify(phc, password) -> bool (constant-time comparison; a string that
asks for more than VERIFY_WORK is refused)
Lanes are filled one after the other in each slice (the result is the same as with
threads); memory is m KiB, allocated per call.
struct Paramscost parametersm_kib: u32-- memory in KiB (at least 8 * lanes)t: u32-- passes over the memoryp: u32-- lanes (parallelism)out_len: u32-- tag length in bytes
impl Params
const INTERACTIVE: Params = Params { m_kib: 19 * 1024, t: 2, p: 1, out_len: 32 }the OWASP recommendation for interactive logins: 19 MiB, 2 passes, 1 laneconst KEY: Params = Params { m_kib: 64 * 1024, t: 3, p: 1, out_len: 32 }for keys that protect data at rest (passphrases): 64 MiB, 3 passes, 1 lanefn argon2id(password: &[u8], salt: &[u8], params: &Params, out: &mut [u8]) -> boolArgon2id with an empty secret and no associated datafn argon2id_ex(password: &[u8], salt: &[u8], secret: &[u8], ad: &[u8], params: &Params, out: &mut [u8]) -> boolArgon2id: false for invalid parameters (out.len() must equal params.out_len)fn hash(password: &[u8], salt: &[u8], params: &Params) -> Option<String>a PHC string of the password with a caller-chosen random salt (>= 16 bytes recommended)fn parse(phc: &str) -> Option<(Params, Vec<u8>, Vec<u8>)>the parameters, salt and tag of a PHC string
/// the most work verify does for a PHC string, in KiB times passes (memory m_kib x passes t):
/// 2^24, so 1 GiB with 16 passes or 64 MiB with 256. A stored string comes from outside; valid()
/// alone let it ask for 4 GiB and 2^32 - 1 passes
VERIFY_WORK: u64 = 1 << 24
fn verify(phc: &str, password: &[u8]) -> boolwhether the password matches a PHC string (false beyond VERIFY_WORK)
crypto/b64.rs#
Source: lib/crypto/b64.rs
b64 -- Base64 (RFC 4648): the standard and the URL-safe alphabet, with or without padding
fn encode(data: &[u8]) -> Stringstandard alphabet, paddedfn encode_nopad(data: &[u8]) -> Stringstandard alphabet, no padding (PHC strings)fn encode_url(data: &[u8]) -> StringURL-safe alphabet, no padding (tokens, ids)fn decode(s: &str) -> Option<Vec<u8>>standard alphabet, padding optionalfn decode_url(s: &str) -> Option<Vec<u8>>URL-safe alphabet, padding optional
crypto/blake2b.rs#
Source: lib/crypto/blake2b.rs
blake2b -- BLAKE2b (RFC 7693): 1..64 byte digests, optional key of up to 64 bytes;
Argon2 builds on it (with its long-output variant `long`)
struct Blake2bBLAKE2b
impl Blake2b
fn new(out_len: usize, key: &[u8]) -> Blake2ba hasher forout_len(1..=64) byte digests, keyed whenkeyis not empty (<= 64 bytes)fn update(&mut self, mut data: &[u8])fn finalize_into(mut self, out: &mut [u8])the digest into out[..out_len]fn finalize(self) -> Vec<u8>fn blake2b(out: &mut [u8], key: &[u8], parts: &[&[u8]])BLAKE2b of the concatenated parts,out.len()(1..=64) bytesfn long(out: &mut [u8], parts: &[&[u8]])Argon2's variable-length hash H' (RFC 9106 3.3) of the concatenated parts
crypto/blake3.rs#
Source: lib/crypto/blake3.rs
blake3 -- BLAKE3: hash, keyed hash, key derivation, extendable output
Blake3::new() / new_keyed(&key) / new_derive_key(context)
update(data); finalize() -> [u8; 32]; finalize_xof(&mut out) (any length)
hash(data) / keyed_hash(&key, data) / derive_key(context, material) -> [u8; 32]
The tree mode of the reference implementation: 1 KiB chunks, a stack of chaining values
merged by the number of finished chunks. Portable code (no SIMD).
struct Blake3an incremental BLAKE3 hasher
impl Blake3
fn new() -> Blake3the plain hash functionfn new_keyed(key: &[u8; 32]) -> Blake3a keyed hash (MAC / PRF) with a 32-byte keyfn new_derive_key(context: &str) -> Blake3key derivation:contextis a hard-coded, unique, application-specific stringfn update(&mut self, mut input: &[u8]) -> &mut Blake3fn finalize(&self) -> [u8; OUT_LEN]the 32-byte digest (the hasher stays usable)fn finalize_xof(&self, out: &mut [u8])any number of output bytes (the first 32 equal finalize())fn finalize_xof_at(&self, offset: u64, out: &mut [u8])output bytes starting at byteoffsetof the output streamfn hash(data: &[u8]) -> [u8; 32]BLAKE3 of a byte stringfn keyed_hash(key: &[u8; 32], data: &[u8]) -> [u8; 32]keyed BLAKE3 (a MAC / PRF)fn derive_key(context: &str, material: &[u8]) -> [u8; 32]a 32-byte key derived from key material for a context string
crypto/bn.rs#
Source: lib/crypto/bn.rs
bn -- unsigned big integers for checking signatures (RSA, ECDSA)
from_be / to_be big-endian bytes <-> little-endian 64-bit limbs
Mont::new(n) arithmetic modulo an odd n: mul (Montgomery), add, sub,
to_mont / from_mont, pow, inv (n prime); pow_ct for a
secret exponent (finite-field Diffie-Hellman)
Variable time on purpose: everything here is public (keys, signatures, digests). Never use
it for secrets -- except pow_ct, which neither branches on nor indexes by the exponent.
type Limbs = Vec<u64>fn from_be(b: &[u8], k: usize) -> Limbsbig-endian bytes -> limbs (at leastkof them)fn to_be(a: &[u64], len: usize) -> Vec<u8>limbs -> exactlylenbig-endian bytes (higher bytes dropped)fn cmp(a: &[u64], b: &[u64]) -> Orderingfn is_zero(a: &[u64]) -> boolfn bits(a: &[u64]) -> usizethe number of significant bitsstruct Montarithmetic modulo an odd numbern: Limbs
impl Mont
fn new(n: &[u64]) -> Option<Mont>fn limbs(&self) -> usizefn mul(&self, a: &[u64], b: &[u64]) -> Limbsa b R^-1 mod n (a, b < n)fn to_mont(&self, a: &[u64]) -> Limbsfn from_mont(&self, a: &[u64]) -> Limbsfn add(&self, a: &[u64], b: &[u64]) -> Limbs(a + b) mod n (a, b < n)fn sub(&self, a: &[u64], b: &[u64]) -> Limbs(a - b) mod n (a, b < n)fn reduce_once(&self, a: &[u64]) -> Limbsa mod n for a < 2 nfn pow(&self, base: &[u64], exp: &[u8]) -> Limbsbase^exp mod n (normal form in and out; exp big-endian)fn pow_ct(&self, base: &[u64], exp: &[u8]) -> Limbsbase^exp mod n for a secret exponent (Diffie-Hellman; base public): windows of four bits, the table entry picked with masks, masked reductions -- the time depends on the lengths onlyfn inv_mont(&self, a: &[u64]) -> Limbsa^-1 mod n for a prime n (a != 0; Montgomery form in and out)
crypto/chacha.rs#
Source: lib/crypto/chacha.rs
chacha -- the ChaCha20 stream cipher (RFC 8439: 256-bit key, 96-bit nonce, 32-bit block
counter), HChaCha20 and XChaCha20 (192-bit nonce; draft-irtf-cfrg-xchacha)
fn block(key: &[u8; 32], counter: u32, nonce: &[u8; 12]) -> [u8; 64]one 64-byte keystream blockfn xor(key: &[u8; 32], counter: u32, nonce: &[u8; 12], data: &mut [u8])XOR the keystream (starting at blockcounter) into datafn hchacha20(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 32]HChaCha20: a subkey from a key and a 128-bit noncefn xchacha_setup(key: &[u8; 32], nonce: &[u8; 24]) -> ([u8; 32], [u8; 12])XChaCha20: the subkey and the ChaCha20 nonce for a 192-bit noncefn xchacha_xor(key: &[u8; 32], counter: u32, nonce: &[u8; 24], data: &mut [u8])XOR the XChaCha20 keystream (starting at blockcounter) into data
crypto/ecdsa.rs#
Source: lib/crypto/ecdsa.rs
ecdsa -- ECDSA on NIST P-256 and P-384 (FIPS 186-5, SEC 1, RFC 6979)
verify(curve, public_key, digest, r, s) public key uncompressed (04 || x || y), checked
to lie on the curve; r, s big-endian integers
verify_p1363(curve, public_key, digest, sig) sig = r || s, each curve.bytes() long (IEEE
P1363: JOSE, COSE, WebCrypto)
sign(curve, secret, hash, digest, extra) -> Option<r || s> deterministic nonces (RFC 6979
with `hash`, the digest's hash); `extra`, when not
empty, goes into the nonce as RFC 6979 3.6's
additional data: 32 random bytes there hedge against
faults and a poor random source alike
public_key(curve, secret) -> Option<04 || x || y> secret_from(curve, random) -> Option<secret>
der_from_p1363(sig) / p1363_from_der(curve, der) r || s <-> the DER Ecdsa-Sig-Value
(strict: minimal lengths and integers, nothing after)
Verification: Jacobian coordinates in the Montgomery domain (a = -3 formulas), u1 G + u2 Q by
Shamir's trick; public data only, variable time. Signing: nist.rs in constant time (complete
formulas, windows read in full, inverses as powers to n - 2); a nonce outside [1, n - 1], or
an r or s of 0, draws the next one as RFC 6979 says (about 2^-32 on P-256, which shows only that
a nonce was refused, nothing of the one taken).
enum CurveP256P384
impl Curve
fn bytes(self) -> usizethe size of a coordinate / scalar in bytesfn verify(curve: Curve, public_key: &[u8], digest: &[u8], r: &[u8], s: &[u8]) -> boolverify an ECDSA signature overdigest(the hash of the message, any length)fn verify_p1363(curve: Curve, public_key: &[u8], digest: &[u8], sig: &[u8]) -> boolverify an r || s signature (IEEE P1363: each half curve.bytes() long)fn der_from_p1363(sig: &[u8]) -> Option<Vec<u8>>the DER Ecdsa-Sig-Value (SEQUENCE { r INTEGER, s INTEGER }) of an r || s signature; None for an empty or odd length, or halves over 125 bytesfn p1363_from_der(curve: Curve, der: &[u8]) -> Option<Vec<u8>>r || s (each curve.bytes() long) from a DER Ecdsa-Sig-Value; None unless it is strict DER: one SEQUENCE of two minimal, non-negative INTEGERs no longer than the curve's size, nothing afterfn secret_from(curve: Curve, random: &[u8]) -> Option<Vec<u8>>a secret key in [1, n - 1] from curve.bytes() random bytes (None: draw again, or another length); only the answer is a branchfn public_key(curve: Curve, secret: &[u8]) -> Option<Vec<u8>>the public key (04 || x || y) of a secret key; None when the secret is not in [1, n - 1]fn sign(curve: Curve, secret: &[u8], hash: HashAlg, digest: &[u8], extra: &[u8]) -> Option<Vec<u8>>sign a digest (hash's output, which RFC 6979 also derives the nonce with): r || s, each curve.bytes() long. None when the secret is not in [1, n - 1] or the digest is not hash.len() bytes. The same secret, digest and extra give the same signature
crypto/ed25519.rs#
Source: lib/crypto/ed25519.rs
ed25519 -- Ed25519 signatures (RFC 8032), strict verification
Keypair::from_seed(&seed) -> Keypair { public } sign(&msg) -> [u8; 64]
verify(&public, &msg, &sig) -> bool
Verification is strict: the public key and R must be canonical points, S must be below the
group order, and [S]B == R + [k]A must hold exactly (no cofactor), so a signature is valid
or not the same way everywhere. The curve constants (d, sqrt(-1), the base point) are
computed from their definitions instead of copied as long numbers.
Scalar multiplication: double and add-always with masked selects (no branches on bits).
struct Keypairan Ed25519 key pair from its 32-byte seed (the private key of RFC 8032)public: [u8; 32]
impl Keypair
fn from_seed(seed: &[u8; 32]) -> Keypairfn seed(&self) -> &[u8; 32]the seed (to store the key)fn sign(&self, msg: &[u8]) -> [u8; 64]fn verify(public: &[u8; 32], msg: &[u8], sig: &[u8; 64]) -> boolstrict verification of a signaturefn valid_public_key(public: &[u8; 32]) -> boolwhether 32 bytes are a valid (canonical, on-curve) public key
crypto/ed448.rs#
Source: lib/crypto/ed448.rs
ed448 -- Ed448 signatures (RFC 8032 5.2), strict verification
Keypair::from_seed(&seed) -> Keypair { public } sign(&msg) -> [u8; 114]
sign_ctx(&msg, &context) -> Option<[u8; 114]> (a context of at most 255 bytes)
verify(&public, &msg, &sig) -> bool verify_ctx(&public, &msg, &context, &sig)
valid_public_key(&public) -> bool
Ed448 over edwards448 (x^2 + y^2 = 1 + d x^2 y^2, d = -39081, p = 2^448 - 2^224 - 1) with
SHAKE256 and dom4 (RFC 8032 2). Keys are 57 bytes, signatures 114 (R || S). Ed448ph (the
pre-hashed variant) is not here.
Verification is strict like ed25519's: the public key and R must be canonical points, S must
be below the group order, and [S]B == R + [k]A must hold exactly (no cofactor).
Field elements: eight 56-bit limbs; 2^448 = 2^224 + 1 folds the upper half of a product into
the lower. Scalar multiplication: double and add-always with masked selects; scalars modulo
L bit-serial with masked subtraction (no branches on secret values). The base point is
decoded from its encoding (RFC 7748's X(P), Y(P)), which checks it is on the curve.
struct Keypairan Ed448 key pair from its 57-byte seed (the private key of RFC 8032)public: [u8; 57]
impl Keypair
fn from_seed(seed: &[u8; 57]) -> Keypairthe key pair of a seed: SHAKE256 of it, the scalar pruned as RFC 8032 5.2.5 saysfn seed(&self) -> &[u8; 57]the seed (to store the key)fn sign(&self, msg: &[u8]) -> [u8; 114]Ed448 with the empty contextfn sign_ctx(&self, msg: &[u8], context: &[u8]) -> Option<[u8; 114]>Ed448 with a context (at most 255 bytes; None for a longer one)fn verify(public: &[u8; 57], msg: &[u8], sig: &[u8; 114]) -> boolstrict verification of an Ed448 signature with the empty contextfn verify_ctx(public: &[u8; 57], msg: &[u8], context: &[u8], sig: &[u8; 114]) -> boolstrict verification with a context (a context over 255 bytes verifies nothing)fn valid_public_key(public: &[u8; 57]) -> boolwhether 57 bytes are a valid (canonical, on-curve) public key
crypto/gcm.rs#
Source: lib/crypto/gcm.rs
gcm -- AES-GCM (NIST SP 800-38D) with 12-byte nonces and 16-byte tags, in constant time
AesGcm::new(key) 16, 24 or 32 bytes (AES-128/192/256-GCM)
seal_in_place(nonce, aad, data) -> tag open_in_place(nonce, aad, data, tag) -> bool
GHASH runs on the bit-reversed form of the blocks, where multiplication in GF(2^128) is a
plain carry-less product modulo x^128 + x^7 + x^2 + x + 1. The carry-less products come from
integer multiplications of operands with three-bit holes (32-bit halves: at most eight
partial products meet in one position, so no carry reaches the next used bit).
struct AesGcm
impl AesGcm
fn new(key: &[u8]) -> Option<AesGcm>fn seal_in_place(&self, nonce: &[u8; 12], aad: &[u8], data: &mut [u8]) -> [u8; 16]encrypt data in place -> the tagfn open_in_place(&self, nonce: &[u8; 12], aad: &[u8], data: &mut [u8], tag: &[u8; 16]) -> boolcheck the tag, then decrypt in place (false: data untouched)
crypto/hmac.rs#
Source: lib/crypto/hmac.rs
hmac -- HMAC (RFC 2104) over any Hash, HKDF (RFC 5869), PBKDF2 (RFC 8018); HMAC-SHA1 and
PBKDF2-HMAC-SHA1 only for protocols defined with them (WPA2-Personal: its PMK, PRF and MIC);
HMAC-MD5 (RFC 2104 with MD5, the vectors of RFC 2202) likewise (RADIUS: the
Message-Authenticator of RFC 3579)
struct Hmac<H: Hash>HMAC with a hash function H
impl<H: Hash> Hmac<H>
fn new(key: &[u8]) -> Hmac<H>fn update(&mut self, data: &[u8])fn finish_into(self, out: &mut [u8])the tag into out[..H::OUT]fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32]HMAC-SHA256 of a messagefn hmac_sha512(key: &[u8], data: &[u8]) -> [u8; 64]HMAC-SHA512 of a messagefn hkdf_extract<H: Hash>(salt: &[u8], ikm: &[u8], prk: &mut [u8])HKDF-Extract: the pseudo-random key (into prk[..H::OUT])fn hkdf_expand<H: Hash>(prk: &[u8], info: &[u8], out: &mut [u8])HKDF-Expand: fillout(at most 255 * H::OUT bytes; panics beyond)fn hkdf_sha256(salt: &[u8], ikm: &[u8], info: &[u8], out: &mut [u8])HKDF-SHA256 (extract and expand)fn hkdf_sha512(salt: &[u8], ikm: &[u8], info: &[u8], out: &mut [u8])HKDF-SHA512 (extract and expand)fn pbkdf2_sha256(password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8])PBKDF2-HMAC-SHA256 (only for importing foreign key files; new keys use Argon2id)fn hmac_sha1(key: &[u8], data: &[u8]) -> [u8; 20]HMAC-SHA1 of a message (older protocols only: WPA2's PRF and MIC)fn pbkdf2<H: Hash>(password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8])PBKDF2 (RFC 8018 5.2) with HMAC over any Hash: fillsout(any length)fn pbkdf2_sha1(password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8])PBKDF2-HMAC-SHA1 (the PMK of WPA2-Personal: passphrase, SSID, 4096 rounds, 32 bytes)fn hmac_md5(key: &[u8], data: &[u8]) -> [u8; 16]HMAC-MD5 of a message (protocols defined with it only: RADIUS' Message-Authenticator)
crypto/p256.rs#
Source: lib/crypto/p256.rs
p256 -- Diffie-Hellman on NIST P-256 (SEC 1, RFC 8446 4.2.8.2) in constant time
public_key(&secret) -> [u8; 65] (panics on an invalid secret) 04 || x || y of secret * G
shared(&secret, &peer_point) -> Option<[u8; 32]> the x coordinate of secret * peer;
None for a point that is not on the curve
secret_from(random) -> Option<[u8; 32]> a scalar in [1, n - 1] from 32 random bytes
The curve as a group, for protocols that compute on points themselves (EAP-PWD: eappwd.rs):
points are x || y (64 bytes, both big endian), scalars 32 bytes big endian
below_p(x) x is a coordinate: smaller than p
y_for_x(x, odd) -> Option<[u8; 32]> the y of a point with this x and parity (None: no such
point); no branch on x before the answer
on_curve(point) both coordinates in range and the curve equation
mul_point(k, point) -> Option<point> k * point (None: not on the curve, or the identity)
add_points(a, b) -> Option<point> a + b (None: not on the curve, or the identity)
neg_point(point) -point
scalar_add(a, b) a + b mod n
scalar_ok(k) k lies in [1, n - 1]
Field elements in Montgomery form with four 64-bit limbs; multiplication, addition and
subtraction without branches on the values (masked final corrections). Points in projective
coordinates with the complete addition formulas of Renes, Costello and Batina (2016,
algorithm 4, a = -3): no exceptional cases, so doubling uses the same formula. Scalar
multiplication by four-bit windows with a table read in full for every window.
fn secret_from(random: &[u8; 32]) -> Option<[u8; 32]>a scalar in [1, n - 1] from random bytes (None: draw again); only the answer is a branchfn public_key(secret: &[u8; 32]) -> [u8; 65]the public key of a secret scalar: 04 || x || yfn below_p(x: &[u8; 32]) -> boolx is smaller than pfn y_for_x(x: &[u8; 32], odd: bool) -> Option<[u8; 32]>the y of the point with this x and whose lowest bit isodd; None when x is out of range or x^3 - 3x + b has no square root (p = 3 mod 4: the root is a^((p + 1) / 4))fn on_curve(p: &[u8; 64]) -> boolboth coordinates are in range and the point is on the curvefn mul_point(k: &[u8; 32], p: &[u8; 64]) -> Option<[u8; 64]>k * point (k below n)fn add_points(a: &[u8; 64], b: &[u8; 64]) -> Option<[u8; 64]>a + bfn neg_point(p: &[u8; 64]) -> [u8; 64]-point (y becomes p - y)fn scalar_add(a: &[u8; 32], b: &[u8; 32]) -> [u8; 32]a + b mod n (both below n)fn scalar_ok(k: &[u8; 32]) -> boolk lies in [1, n - 1]
crypto/p384.rs#
Source: lib/crypto/p384.rs
p384 -- Diffie-Hellman on NIST P-384 (SEC 1, RFC 8446 4.2.8.2) in constant time
public_key(&secret) -> [u8; 97] (panics on an invalid secret) 04 || x || y of secret * G
shared(&secret, &peer_point) -> Option<[u8; 48]> the x coordinate of secret * peer;
None for a point that is not on the curve
secret_from(random) -> Option<[u8; 48]> a scalar in [1, n - 1] from 48 random bytes
The arithmetic is nist.rs's: six limbs in Montgomery form, complete addition formulas,
four-bit windows that read the whole table.
fn secret_from(random: &[u8; 48]) -> Option<[u8; 48]>a scalar in [1, n - 1] from random bytes (None: draw again); only the answer is a branchfn public_key(secret: &[u8; 48]) -> [u8; 97]the public key of a secret scalar: 04 || x || y
crypto/poly1305.rs#
Source: lib/crypto/poly1305.rs
poly1305 -- the Poly1305 one-time authenticator (RFC 8439), 44/44/42-bit limbs
struct Poly1305a Poly1305 state for one message under a one-time key
impl Poly1305
fn new(key: &[u8; 32]) -> Poly1305fn update(&mut self, mut data: &[u8])fn pad16(&mut self)feed zero bytes up to the next multiple of 16 (the AEAD padding)fn finalize(mut self) -> [u8; 16]fn poly1305(key: &[u8; 32], msg: &[u8]) -> [u8; 16]the Poly1305 tag of a message
crypto/rsa.rs#
Source: lib/crypto/rsa.rs
rsa -- RSA signatures (RFC 8017): PKCS #1 v1.5 and PSS verification with MGF1, PKCS #1 v1.5
and PSS signing, key generation
PublicKey::new(n, e) big-endian modulus (1024..8192 bits) and exponent
key.verify_pkcs1(hash, digest, sig) the encoding is rebuilt and compared whole
key.verify_pss(hash, digest, sig, salt) salt length given, or None: any
PrivateKey::generate(bits, rand) exponent 65537, two primes of bits / 2 from the
caller's random bytes (the same bytes give the
same key)
PrivateKey::from_parts(n, e, d, p, q) big-endian numbers, checked against each other
key.sign_pkcs1(hash, digest) RSASSA-PKCS1-v1_5; the exponent in constant time
key.sign_pss(hash, digest, salt) RSASSA-PSS with MGF1 of the same hash and the
caller's salt (hash.len() random bytes, as TLS 1.3
and X.509 use; empty: the same signature each time)
key.n() / e() / d() / p() / q() / iqmp() big-endian without leading zeros
key.dp() / dq() d mod (p - 1), d mod (q - 1) (PKCS #1's
RSAPrivateKey; one bit of d at a time, the
subtraction kept by mask)
Public operations are variable time (that is fine for them). Signing uses pow_ct; generate is
variable time and meant for simulators and tests, where the random bytes are no secret either.
struct PublicKey
impl PublicKey
fn new(n: &[u8], e: &[u8]) -> Option<PublicKey>fn bits(&self) -> usizefn verify_pkcs1(&self, hash: HashAlg, digest: &[u8], sig: &[u8]) -> boolRSASSA-PKCS1-v1_5 (the DigestInfo with or without the NULL parameter)fn verify_pkcs1_sha1(&self, digest: &[u8], sig: &[u8]) -> boolRSASSA-PKCS1-v1_5 with SHA-1 (a 20-byte digest): only for protocols defined with it, as DNSSEC's algorithms 5 and 7 (RFC 3110, 5155), which RFC 9905 deprecates; HashAlg has no SHA-1, so nothing else signs or verifies with it by accidentfn verify_pss(&self, hash: HashAlg, digest: &[u8], sig: &[u8], salt_len: Option<usize>) -> boolRSASSA-PSS with MGF1 of the same hashfn mgf1(hash: HashAlg, seed: &[u8], len: usize) -> Vec<u8>MGF1 (RFC 8017 B.2.1)struct PrivateKeyan RSA private key
impl PrivateKey
fn generate(bits: usize, rand: &mut dyn FnMut(&mut [u8])) -> Option<PrivateKey>a new key ofbitsbits (1024 to 8192, a multiple of 16): exponent 65537, primes made fromrandfn from_parts(n: &[u8], e: &[u8], d: &[u8], p: &[u8], q: &[u8]) -> Option<PrivateKey>a key from its numbers (big-endian); None when p q is not n, or d does not undo e for a test valuefn bits(&self) -> usizethe modulus's bitsfn n(&self) -> Vec<u8>the modulus, big-endianfn e(&self) -> &[u8]fn d(&self) -> &[u8]fn p(&self) -> &[u8]fn q(&self) -> &[u8]fn iqmp(&self) -> Vec<u8>q^-1 mod p, big-endian (what key files keep beside the primes): q is reduced mod p first (a masked remainder), so the primes may come in either order and of any lengthsfn dp(&self) -> Vec<u8>d mod (p - 1)fn dq(&self) -> Vec<u8>d mod (q - 1)fn public(&self) -> Option<PublicKey>the public halffn sign_pkcs1(&self, hash: HashAlg, digest: &[u8]) -> Option<Vec<u8>>RSASSA-PKCS1-v1_5 of a digest: k bytes (None: the digest has the wrong length or the modulus is too short for it)fn sign_pss(&self, hash: HashAlg, digest: &[u8], salt: &[u8]) -> Option<Vec<u8>>RSASSA-PSS of a digest (EMSA-PSS, RFC 8017 9.1.1) with MGF1 of the same hash: k bytes. None when the digest has the wrong length or the modulus is too short for digest and salt
crypto/sealbox.rs#
Source: lib/crypto/sealbox.rs
sealbox -- anonymous public-key encryption: whoever holds the recipient's X25519 public key
can seal, only the secret key opens. (Recovery kits: the repository key sealed to an
offline key pair.)
sealed = ephemeral public (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, aad, plain)
key = HKDF-SHA256(salt = ephemeral public ‖ recipient public,
ikm = X25519(ephemeral secret, recipient public),
info = "JFLib sealbox v1")
OVERHEAD: usize = 32 + 24 + 16
fn seal(recipient: &[u8; 32], random: &[u8; 56], aad: &[u8], plain: &[u8]) -> Option<Vec<u8>>sealplainforrecipient;random= 32 bytes ephemeral secret ‖ 24 bytes nonce (None: a degenerate recipient key)fn open(secret: &[u8; 32], aad: &[u8], sealed: &[u8]) -> Option<Vec<u8>>open a sealed box with the recipient's secret key (None: not for this key or altered)
crypto/sha2.rs#
Source: lib/crypto/sha2.rs
sha2 -- SHA-224, SHA-256, SHA-384 and SHA-512 (FIPS 180-4), streaming and one-shot
struct Sha256SHA-256
impl Sha256
const fn new() -> Sha256fn update(&mut self, mut data: &[u8])fn finalize(mut self) -> [u8; 32]struct Sha224(Sha256)SHA-224 (SHA-256 with its own initial value, cut to 28 bytes)
impl Sha224
const fn new() -> Sha224fn update(&mut self, data: &[u8])fn finalize(self) -> [u8; 28]struct Sha512SHA-512
impl Sha512
const fn new() -> Sha512fn update(&mut self, mut data: &[u8])fn finalize(mut self) -> [u8; 64]struct Sha384(Sha512)SHA-384 (SHA-512 with its own initial value, cut to 48 bytes)
impl Sha384
const fn new() -> Sha384fn update(&mut self, data: &[u8])fn finalize(self) -> [u8; 48]fn sha224(data: &[u8]) -> [u8; 28]SHA-224 of a byte stringfn sha256(data: &[u8]) -> [u8; 32]SHA-256 of a byte stringfn sha384(data: &[u8]) -> [u8; 48]SHA-384 of a byte stringfn sha512(data: &[u8]) -> [u8; 64]SHA-512 of a byte string
crypto/sha3.rs#
Source: lib/crypto/sha3.rs
sha3 -- SHA-3 and SHAKE (FIPS 202), streaming and one-shot
Sha3_224 / Sha3_256 / Sha3_384 / Sha3_512 new, update, finalize; sha3_224(data) .. sha3_512
Shake128 / Shake256 new, update, finalize_xof -> ShakeReader::read(out)
(any length, read in as many calls as wanted);
shake128(data, out) / shake256(data, out)
Keccak-f[1600] on 25 64-bit lanes: no tables, no branches on the data. The state is
overwritten when a hash is dropped (ML-KEM and HMAC put secrets through it).
struct ShakeReader(Sponge)the output of a SHAKE: read as much as wanted, in pieces or at once (the same bytes)
impl ShakeReader
fn read(&mut self, out: &mut [u8])the next out.len() bytes
crypto/x25519.rs#
Source: lib/crypto/x25519.rs
x25519 -- Diffie-Hellman on Curve25519 (RFC 7748): Montgomery ladder with masked swaps
public_key(&secret) -> [u8; 32]
shared(&secret, &their_public) -> Option<[u8; 32]> (None: an all-zero result, i.e. a
low-order point was offered)
fn x25519(k: &[u8; 32], u: &[u8; 32]) -> [u8; 32]the scalar multiplication k * u (k clamped as RFC 7748 requires)fn public_key(secret: &[u8; 32]) -> [u8; 32]the public key of a 32-byte secret
crypto/sha1.rs#
Source: lib/crypto/sha1.rs
sha1 -- SHA-1 (FIPS 180-4), streaming and one-shot: only for protocols that are defined with
it (WPA2's PBKDF2 and PRF, HMAC-SHA1 of older standards); it is broken for collisions, so
new designs take SHA-256
struct Sha1SHA-1
impl Sha1
const fn new() -> Sha1fn update(&mut self, mut data: &[u8])fn finalize(mut self) -> [u8; 20]fn sha1(data: &[u8]) -> [u8; 20]SHA-1 of a byte string
crypto/keywrap.rs#
Source: lib/crypto/keywrap.rs
keywrap -- the AES key wrap of RFC 3394 (the default initial value A6A6A6A6A6A6A6A6): keys
that travel encrypted under a key-encrypting key, as WPA2 and WPA3 hand the group key to a
station in message 3 of the 4-way handshake
aes_wrap(kek, plain) -> Option<Vec<u8>> plain: a multiple of 8 bytes, at least 16;
the result is 8 bytes longer
aes_unwrap(kek, wrapped) -> Option<Vec<u8>> None when the integrity check fails
kek is a 16-, 24- or 32-byte AES key.
fn aes_wrap(kek: &[u8], plain: &[u8]) -> Option<Vec<u8>>wrapsplain(n * 8 bytes, n >= 2) underkekfn aes_unwrap(kek: &[u8], wrapped: &[u8]) -> Option<Vec<u8>>unwraps what aes_wrap made; None when it is not a multiple of 8 bytes of at least 24 or the check value does not come out
crypto/cmac.rs#
Source: lib/crypto/cmac.rs
cmac -- AES-CMAC (RFC 4493, NIST SP 800-38B): a message authentication code from the AES
block cipher, as the MIC of WPA3-Personal's 4-way handshake (AKM 8) and of 802.11w use it
cmac_aes(key, data) -> Option<[u8; 16]> key: 16, 24 or 32 bytes (AES-128/192/256); None otherwise
fn cmac_aes(key: &[u8], data: &[u8]) -> Option<[u8; 16]>the CMAC ofdataunderkey
crypto/md5.rs#
Source: lib/crypto/md5.rs
md5 -- MD5 (RFC 1321), streaming and one-shot: only for protocols that are defined with it
(RADIUS: the authenticators and the hiding of User-Password of RFC 2865, HMAC-MD5 for the
Message-Authenticator of RFC 3579); it is broken for collisions, so new designs take SHA-256
Md5::new() / update(data) / finalize() -> [u8; 16]
md5(data) one byte string
md5_parts(parts) the concatenation of several, without copying them together (what
RADIUS hashes: code, identifier, length, authenticator, attributes,
secret)
struct Md5MD5
impl Md5
const fn new() -> Md5fn update(&mut self, mut data: &[u8])fn finalize(mut self) -> [u8; 16]the digest: the padding of RFC 1321 3.1, the bit length little-endian (3.2)fn md5(data: &[u8]) -> [u8; 16]MD5 of a byte stringfn md5_parts(parts: &[&[u8]]) -> [u8; 16]MD5 of the concatenation ofparts
crypto/mlkem.rs#
Source: lib/crypto/mlkem.rs
mlkem -- ML-KEM (FIPS 203), the module-lattice key encapsulation: ML-KEM-512, -768 and -1024
Params::MlKem512 / MlKem768 / MlKem1024 .ek_len() .dk_len() .ct_len() (bytes)
keygen(params, &seed) -> (ek, dk) seed = d || z, 64 random bytes (FIPS 203's seed
form: a key may be kept as these 64 bytes)
encaps(params, ek, &m) -> Option<(ct, key)> m: 32 random bytes; None when ek has the wrong
length or a coefficient of q or more (FIPS 203 7.2)
decaps(params, dk, ct) -> Option<key> None when a length is wrong or dk's hash of its
encapsulation key does not match (7.3); a
ciphertext that does not re-encrypt to itself
gives the implicit-rejection key J(z || ct),
which nothing tells apart from a key
The secret paths (keygen's s and e, encryption's y, decapsulation's message and the choice
between its two keys) have no branch and no table lookup on secret data, and no division:
reductions modulo q = 3329 are Barrett's with a masked correction, and Compress divides by q
the same way (KyberSlash, 2024: a division by q compiled to a div instruction whose time
depends on its operand). The matrix comes from the public seed rho, so its rejection
sampling may branch.
enum Paramsthe parameter sets of FIPS 203, table 2MlKem512MlKem768MlKem1024
impl Params
fn ek_len(self) -> usizethe encapsulation key's length: 384 k + 32fn dk_len(self) -> usizethe decapsulation key's length: 768 k + 96fn ct_len(self) -> usizethe ciphertext's length: 32 (du k + dv)fn keygen(params: Params, seed: &[u8; 64]) -> (Vec<u8>, Vec<u8>)ML-KEM.KeyGen from the 64-byte seed d || z: (encapsulation key, decapsulation key)fn encaps(params: Params, ek: &[u8], m: &[u8; 32]) -> Option<(Vec<u8>, [u8; 32])>ML-KEM.Encaps with the 32 random bytes m: (ciphertext, shared key)fn decaps(params: Params, dk: &[u8], ct: &[u8]) -> Option<[u8; 32]>ML-KEM.Decaps: the shared key (implicit rejection for a ciphertext that does not re-encrypt)
crypto/eappwd.rs#
Source: lib/crypto/eappwd.rs
eappwd -- the sums of EAP-PWD (RFC 5931) on group 19 (P-256) with HMAC-SHA-256 as the random
function and the PRF: a password-only EAP method that needs no certificates and derives an
MSK and an EMSK. Nothing of its packets here (netpkt::eap) and no state (eapm)
GROUP, RAND_FUNC, PRF the ciphersuite this knows; ciphersuite() its bytes
kdf(key, label, n) n bytes of the KDF of RFC 5931 2.5
pwe(token, peer_id, server_id, password) the password element: hunting and pecking (2.8.3),
at least ROUNDS rounds
commit(pwe, rand, mask) (Scalar, Element) of one side, from its two random
scalars (2.8.5.1); None to draw again
shared(pwe, rand, peer_scalar, peer_element) ss, the x coordinate of k (2.8.5.2); None for
what a peer must not send
confirm(ss, element_a, scalar_a, element_b, scalar_b) H(ss | own | other's | ciphersuite)
(2.8.5.3)
keys(ss, confirm_p, confirm_s, scalar_p, scalar_s) (MSK, EMSK) (2.9)
H(x) is HMAC-SHA-256 with a key of 32 zero bytes. The plain search would show by its time how
many rounds a password needs (Dragonblood, CVE-2019-9494); as RFC 8146 and hostapd, pwe runs
ROUNDS rounds whatever round found the point, keeps the first one without a branch on it and
only goes on beyond ROUNDS in the case (about 2^-40) that none of them found one. The point is
the same as the plain search's.
/// the group's number in IANA's registry: P-256
GROUP: u16 = 19
/// the random function: HMAC-SHA-256
RAND_FUNC: u8 = 1
/// the PRF: HMAC-SHA-256
PRF: u8 = 1
/// the rounds pwe always runs (k = 40 of RFC 8146 and hostapd)
ROUNDS: u8 = 40
fn ciphersuite() -> [u8; 4]group | random function | PRFfn kdf(key: &[u8], label: &[u8], n: usize) -> Vec<u8>K(i) = HMAC(key, K(i-1) | i | label | L) with i and L (in bits) as 16-bit numbers, as many of them asnbytes takefn pwe(token: &[u8; 4], peer_id: &[u8], server_id: &[u8], password: &[u8]) -> [u8; 64]the password element: a point both sides find from the password and their names; the counter starts at 1, the lowest bit of pwd-seed picks y; the first round's point that has one, after ROUNDS rounds in any casefn commit(pwe: &[u8; 64], rand: &[u8; 32], mask: &[u8; 32]) -> Option<([u8; 32], [u8; 64])>Scalar = rand + mask mod n, Element = -(mask * PWE); None when a random value is no scalar or Scalar comes to 0 or 1fn confirm(ss: &[u8; 32], element_a: &[u8; 64], scalar_a: &[u8; 32], element_b: &[u8; 64], scalar_b: &[u8; 32]) -> [u8; 32]Confirm of a side: H(ss | its element | its scalar | the other's element | scalar | ciphersuite)fn keys(ss: &[u8; 32], confirm_p: &[u8; 32], confirm_s: &[u8; 32], scalar_p: &[u8; 32], scalar_s: &[u8; 32]) -> ([u8; 64], [u8; 64])MK = H(ss | Confirm_P | Confirm_S), stretched with the session id (the type byte 52 and H(ciphersuite | Scalar_P | Scalar_S)) to 128 bytes: the MSK, then the EMSK