1#[expect(unused_imports, reason = "imported module dependencies")]
23use crate::utilities::*;
24
25use crate::utilities::password::Password;
26use anyhow::Result;
27use argon2::Argon2;
28#[cfg(any(debug_assertions, test))]
29use argon2::password_hash::PasswordHash;
30use argon2::password_hash::SaltString;
31use argon2::password_hash::rand_core::OsRng;
32use serde::{Deserialize, Serialize};
33use zeroize::ZeroizeOnDrop;
34
35#[derive(Debug, Clone, Serialize, Deserialize, ZeroizeOnDrop, PartialEq)]
39pub struct KekParams {
40 pub salt: Vec<u8>,
41 pub m_cost: u32,
43 pub t_cost: u32,
44 pub p_cost: u32,
45}
46
47pub fn derive_kek(password: &Password) -> Result<(Vec<u8>, KekParams)> {
56 #[cfg(any(debug_assertions, test))]
58 {
59 if password.password == crate::user::TEST_USER_PASS.as_bytes() {
60 use crate::utilities::password::TEST_USER_PHC;
63 let parsed = PasswordHash::new(TEST_USER_PHC)
64 .map_err(|e| anyhow::anyhow!("Failed to parse PHC: {e}"))?;
65 let salt_bytes = &mut [0u8; 16];
66 let salt = parsed.salt.ok_or_else(|| {
67 anyhow::anyhow!("Could not decode test password salt")
68 })?;
69 salt.decode_b64(salt_bytes)
70 .map_err(|e| anyhow::anyhow!("Failed to decode salt: {e}"))?;
71 let output_key_material =
73 parsed.hash.as_ref().map_or_else(
74 Vec::new,
75 |h: &argon2::password_hash::Output| h.as_bytes().to_vec(),
76 );
77 return Ok((
78 output_key_material,
79 KekParams {
80 m_cost: parsed
82 .params
83 .get("m")
84 .map_or(19456, |v| v.decimal().unwrap_or(19456)),
85 t_cost: parsed
87 .params
88 .get("t")
89 .map_or(2, |v| v.decimal().unwrap_or(2)),
90 p_cost: parsed
92 .params
93 .get("p")
94 .map_or(1, |v| v.decimal().unwrap_or(1)),
95 salt: salt_bytes.to_vec(),
96 },
97 ));
98 }
99 }
100 let mut output_key_material = vec![0u8; 32];
102 let salt = SaltString::generate(&mut OsRng);
103 let mut salt_bytes = [0u8; 16];
105 salt.decode_b64(&mut salt_bytes)
106 .map_err(|e| anyhow::anyhow!("Failed to decode salt: {e}"))?;
107 let hasher = Argon2::default();
108 let params = hasher.params();
109 hasher
110 .hash_password_into(
111 &password.password,
112 &salt_bytes,
113 &mut output_key_material,
114 )
115 .map_err(|e| anyhow::anyhow!("Failed to derive KEK: {e:?}"))?;
116 Ok((
117 output_key_material,
118 KekParams {
119 salt: salt_bytes.to_vec(),
120 m_cost: params.m_cost(),
121 t_cost: params.t_cost(),
122 p_cost: params.p_cost(),
123 },
124 ))
125}
126
127pub fn derive_kek_with_params(
131 password: &Password,
132 params: &KekParams,
133) -> Result<Vec<u8>> {
134 #[cfg(any(debug_assertions, test))]
136 {
137 if password.password == crate::user::TEST_USER_PASS.as_bytes() {
138 let parsed =
139 PasswordHash::new(crate::utilities::password::TEST_USER_PHC)
140 .map_err(|e| anyhow::anyhow!("Failed to parse PHC: {e}"))?;
141 let hash = parsed
142 .hash
143 .ok_or_else(|| anyhow::anyhow!("Missing hash in PHC"))?;
144 let output_key_material = hash.as_bytes().to_vec();
145 return Ok(output_key_material);
146 }
147 }
148
149 let mut output_key_material = vec![0u8; 32];
150 let argon2_params = argon2::Params::new(
151 params.m_cost,
152 params.t_cost,
153 params.p_cost,
154 Some(output_key_material.len()),
155 )
156 .map_err(|e| anyhow::anyhow!("Invalid Argon2 params: {e:?}"))?;
157
158 let hasher = Argon2::new(
159 argon2::Algorithm::Argon2id,
160 argon2::Version::V0x13,
161 argon2_params,
162 );
163 hasher
164 .hash_password_into(
165 &password.password,
166 ¶ms.salt,
167 &mut output_key_material,
168 )
169 .map_err(|e| anyhow::anyhow!("Failed to derive KEK: {e:?}"))?;
170
171 Ok(output_key_material)
172}
173
174pub fn generate_dek() -> Result<Vec<u8>> {
177 crate::utilities::rand_bytes(32)
178}
179
180pub fn wrap_key(kek: &[u8], dek: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
184 use aes_gcm::{
185 Aes256Gcm, Nonce,
186 aead::{Aead, KeyInit, Payload},
187 };
188
189 let nonce_bytes = crate::utilities::rand_bytes(12)?;
191 let nonce = Nonce::try_from(nonce_bytes.as_slice())
192 .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
193
194 let cipher = Aes256Gcm::new_from_slice(kek).map_err(|e| {
195 anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
196 })?;
197
198 let payload = Payload { msg: dek, aad };
199 let ciphertext = cipher
200 .encrypt(&nonce, payload)
201 .map_err(|e| anyhow::anyhow!("DEK encryption failed: {e:?}"))?;
202
203 let mut out = nonce_bytes;
204 out.extend_from_slice(&ciphertext);
205 Ok(out)
206}
207
208pub fn unwrap_key(kek: &[u8], wrapped: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
211 use aes_gcm::{
212 Aes256Gcm, Nonce,
213 aead::{Aead, KeyInit, Payload},
214 };
215
216 if wrapped.len() < 12 {
217 anyhow::bail!("Invalid wrapped key length");
218 }
219
220 let (nonce_bytes, ciphertext) = wrapped.split_at(12);
221 let nonce = Nonce::try_from(nonce_bytes)
222 .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
223
224 let cipher = Aes256Gcm::new_from_slice(kek).map_err(|e| {
225 anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
226 })?;
227
228 let payload = Payload {
229 msg: ciphertext,
230 aad,
231 };
232 let plaintext = cipher
233 .decrypt(&nonce, payload)
234 .map_err(|e| anyhow::anyhow!("DEK decryption failed: {e:?}"))?;
235
236 Ok(plaintext)
237}
238
239pub fn seal_bytes(key: &[u8], aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>> {
242 use aes_gcm::{
243 Aes256Gcm, Nonce,
244 aead::{Aead, KeyInit, Payload},
245 };
246
247 let nonce_bytes = crate::utilities::rand_bytes(12)?;
248 let nonce = Nonce::try_from(nonce_bytes.as_slice())
249 .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
250
251 let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| {
252 anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
253 })?;
254
255 let payload = Payload {
256 msg: plaintext,
257 aad,
258 };
259 let ciphertext = cipher
260 .encrypt(&nonce, payload)
261 .map_err(|e| anyhow::anyhow!("Encryption failed: {e:?}"))?;
262
263 let mut out = nonce_bytes;
264 out.extend_from_slice(&ciphertext);
265 Ok(out)
266}
267
268pub fn open_bytes(
271 key: &[u8],
272 aad: &[u8],
273 ciphertext: &[u8],
274) -> Result<Vec<u8>> {
275 use aes_gcm::{
276 Aes256Gcm, Nonce,
277 aead::{Aead, KeyInit, Payload},
278 };
279
280 if ciphertext.len() < 12 {
281 anyhow::bail!("Invalid ciphertext length");
282 }
283
284 let (nonce_bytes, ciphertext_actual) = ciphertext.split_at(12);
285 let nonce = Nonce::try_from(nonce_bytes)
286 .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
287
288 let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| {
289 anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
290 })?;
291
292 let payload = Payload {
293 msg: ciphertext_actual,
294 aad,
295 };
296 let plaintext = cipher
297 .decrypt(&nonce, payload)
298 .map_err(|e| anyhow::anyhow!("Decryption failed: {e:?}"))?;
299
300 Ok(plaintext)
301}