capsule_core/crypto/
pwkdf.rs1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct WrappedSecret {
26 pub mem_kib: u32,
28 pub t_cost: u32,
30 pub p_cost: u32,
32 pub salt: [u8; 32],
34 pub nonce: [u8; 12],
36 pub ciphertext: Vec<u8>,
38}
39
40pub 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
60pub 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
83pub fn wrap(
85 secret: &[u8],
86 passphrase: &[u8],
87 tier: DeviceTier,
88) -> Result<WrappedSecret, CryptoError> {
89 wrap_with(secret, passphrase, tier.params())
90}
91
92pub 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;