Skip to main content

capsule_core/crypto/
kdf.rs

1//! HKDF-SHA512 key derivation (SSoT: [Cryptography — Primitives § Key Derivation]).
2//!
3//! The wider SHA-512 keeps the post-quantum posture (a 256-bit hash falls to ~128-bit
4//! under Grover; SHA-512 retains ~256-bit), and KDFs are off the hot path. Every
5//! derivation includes a versioned `info` label (see [`super::primitives::info`]) and a
6//! scope-unique salt (`album_id`, `file_id`, `blob_id`) — salts are never reused across
7//! scopes. The 512-bit output is truncated to 32 bytes for AES-256 keys.
8//!
9//! [Cryptography — Primitives § Key Derivation]: https://docs/design/cryptography/primitives/#key-derivation
10
11use hkdf::Hkdf;
12use sha2::Sha512;
13
14/// HKDF-SHA512 extract-then-expand, producing `out_len` bytes.
15///
16/// `out_len` must be ≤ 255 × 64 (the HKDF-SHA512 ceiling), which every Capsule
17/// derivation satisfies; an out-of-range request is a programming error and panics.
18pub fn hkdf_sha512(ikm: &[u8], salt: &[u8], info: &[u8], out_len: usize) -> Vec<u8> {
19    let hk = Hkdf::<Sha512>::new(Some(salt), ikm);
20    let mut okm = vec![0u8; out_len];
21    hk.expand(info, &mut okm)
22        .expect("HKDF-SHA512 output length within bounds");
23    okm
24}
25
26/// Derive a 32-byte (AES-256) key. The canonical derivation for file and metadata-blob keys.
27pub fn derive_key32(ikm: &[u8], salt: &[u8], info: &[u8]) -> [u8; 32] {
28    let okm = hkdf_sha512(ikm, salt, info, 32);
29    let mut key = [0u8; 32];
30    key.copy_from_slice(&okm);
31    key
32}
33
34#[cfg(test)]
35mod tests;