Skip to main content

capsule_core/crypto/
pwkdf.rs

1//! Password-based key wrapping: Argon2id derives a wrapping key from a passphrase /
2//! recovery code, which then seals a secret under AES-256-GCM. Used for the master-key
3//! escrow and backup wrap key (SSoT: [Cryptography — Primitives § Password-based KDF]).
4//!
5//! Argon2id runs only at account recovery and device bootstrap — never on a hot path.
6//! The cost parameters are recorded **inside** the wrapped blob, so a desktop-wrapped
7//! blob unwraps correctly on a phone (slowly) and vice versa, and parameters can be
8//! raised over time without a flag day.
9//!
10//! [Cryptography — Primitives § Password-based KDF]: https://docs/design/cryptography/primitives/#password-based-kdf
11
12use aes_gcm::aead::{Aead, KeyInit};
13use aes_gcm::{Aes256Gcm, Key, Nonce};
14use argon2::{Algorithm, Argon2, Params, Version};
15use serde::{Deserialize, Serialize};
16
17use super::primitives::{Argon2Params, DeviceTier};
18use super::{CryptoError, rng};
19
20/// A secret sealed under a passphrase-derived key, self-describing for unwrap.
21///
22/// The Argon2id parameters and salt travel with the ciphertext so any device can
23/// reconstruct the wrapping key from the passphrase alone.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct WrappedSecret {
26    /// Argon2id memory cost (KiB) used at wrap time.
27    pub mem_kib: u32,
28    /// Argon2id iteration cost `t`.
29    pub t_cost: u32,
30    /// Argon2id parallelism `p`.
31    pub p_cost: u32,
32    /// 32-byte CSPRNG salt for Argon2id.
33    pub salt: [u8; 32],
34    /// 12-byte AES-256-GCM nonce.
35    pub nonce: [u8; 12],
36    /// AES-256-GCM ciphertext of the secret (includes the 16-byte tag).
37    pub ciphertext: Vec<u8>,
38}
39
40/// Derive a 32-byte wrapping key from a passphrase and salt via Argon2id. Exposed so the
41/// backup artifact can use one passphrase-derived key for both its MANIFEST HMAC and its
42/// AMK-ledger seal (SSoT: [Backup — Master-Key Escrow]).
43///
44/// [Backup — Master-Key Escrow]: https://docs/design/backup-recovery/#master-key-escrow
45pub fn derive_wrap_key(
46    passphrase: &[u8],
47    salt: &[u8],
48    p: Argon2Params,
49) -> Result<[u8; 32], CryptoError> {
50    let params = Params::new(p.mem_kib, p.t_cost, p.p_cost, Some(32))
51        .map_err(|_| CryptoError::Key("invalid Argon2 parameters"))?;
52    let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
53    let mut key = [0u8; 32];
54    argon
55        .hash_password_into(passphrase, salt, &mut key)
56        .map_err(|_| CryptoError::Key("Argon2id derivation failed"))?;
57    Ok(key)
58}
59
60/// Wrap `secret` under `passphrase` with explicit Argon2id parameters (recorded in-band).
61pub fn wrap_with(
62    secret: &[u8],
63    passphrase: &[u8],
64    params: Argon2Params,
65) -> Result<WrappedSecret, CryptoError> {
66    let salt = rng::random_array::<32>();
67    let nonce = rng::random_array::<12>();
68    let wrap_key = derive_wrap_key(passphrase, &salt, params)?;
69    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&wrap_key));
70    let ciphertext = cipher
71        .encrypt(Nonce::from_slice(&nonce), secret)
72        .map_err(|_| CryptoError::Auth("AES-GCM wrap failed"))?;
73    Ok(WrappedSecret {
74        mem_kib: params.mem_kib,
75        t_cost: params.t_cost,
76        p_cost: params.p_cost,
77        salt,
78        nonce,
79        ciphertext,
80    })
81}
82
83/// Wrap `secret` under `passphrase` using the canonical parameters for `tier`.
84pub fn wrap(
85    secret: &[u8],
86    passphrase: &[u8],
87    tier: DeviceTier,
88) -> Result<WrappedSecret, CryptoError> {
89    wrap_with(secret, passphrase, tier.params())
90}
91
92/// Unwrap a [`WrappedSecret`], re-deriving the wrapping key from the in-band parameters.
93/// Returns [`CryptoError::Auth`] on a wrong passphrase or a corrupt/tampered blob.
94pub fn unwrap(blob: &WrappedSecret, passphrase: &[u8]) -> Result<Vec<u8>, CryptoError> {
95    let params = Argon2Params {
96        mem_kib: blob.mem_kib,
97        t_cost: blob.t_cost,
98        p_cost: blob.p_cost,
99    };
100    let wrap_key = derive_wrap_key(passphrase, &blob.salt, params)?;
101    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&wrap_key));
102    cipher
103        .decrypt(Nonce::from_slice(&blob.nonce), blob.ciphertext.as_slice())
104        .map_err(|_| CryptoError::Auth("unwrap: wrong passphrase or corrupt blob"))
105}
106
107#[cfg(test)]
108mod tests;