1use crate::Error;
2use aes_gcm::{
3 Aes256Gcm,
4 aead::{Aead, KeyInit, Payload},
5};
6use argon2::{Algorithm::Argon2id as Argon2Algo, Argon2, Params, Version::V0x13 as Argon2V};
7use chacha20poly1305::ChaCha20Poly1305;
8use serde::{Deserialize, Serialize};
9use tap::prelude::*;
10use zeroize::Zeroizing;
11
12const NONCE_SIZE: usize = 12;
13const SALT_SIZE: usize = 32;
14pub const KEY_SIZE: usize = 32;
15pub const STREAM_CHUNK: usize = 64 * 1024;
16pub const STREAM_TAG: usize = 16;
17const STREAM_NONCE_SIZE: usize = 7;
18const ARGON2_M_COST_KIB: u32 = 65536;
19const ARGON2_T_COST: u32 = 3;
20const ARGON2_P_COST: u32 = 1;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, derive_more::Display)]
23pub enum CipherType {
24 ChaCha20Poly1305 = 0,
25 Aes256Gcm = 1,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, derive_more::Display)]
29pub enum Kdf {
30 Argon2id = 0,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct EncryptedNote {
35 pub cipher: CipherType,
36 pub nonce: Vec<u8>,
37 pub ciphertext: Vec<u8>,
38 pub salt: Vec<u8>,
39 pub kdf: Kdf,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum ChunkKind {
44 NonLast,
45 Last,
46}
47
48fn chunk_position(position: usize) -> Result<u32, Error> {
49 u32::try_from(position).map_err(|e| Error::Convert {
50 context: "chunk count exceeds u32 range",
51 source: e,
52 })
53}
54
55fn stream_nonce(base: &[u8], position: u32, kind: ChunkKind) -> [u8; 12] {
56 let mut nonce = [0u8; 12];
57 nonce[..STREAM_NONCE_SIZE].copy_from_slice(base);
58 nonce[STREAM_NONCE_SIZE..11].copy_from_slice(&position.to_be_bytes());
59 nonce[11] = match kind {
60 ChunkKind::NonLast => 0,
61 ChunkKind::Last => 1,
62 };
63 nonce
64}
65
66pub struct StreamParts {
67 cipher: CipherType,
68 key: Zeroizing<Vec<u8>>,
69 nonce: Vec<u8>,
70 salt: Vec<u8>,
71 aad: Vec<u8>,
72}
73
74impl StreamParts {
75 pub fn derive(password: &str, cipher: CipherType, aad: &[u8]) -> Result<Self, Error> {
76 let salt = random_vec(SALT_SIZE)?;
77 let nonce = random_vec(STREAM_NONCE_SIZE)?;
78 let key = Zeroizing::new(derive_key(password, &salt, Kdf::Argon2id)?);
79 Ok(Self {
80 cipher,
81 key,
82 nonce,
83 salt,
84 aad: aad.to_vec(),
85 })
86 }
87
88 pub fn recover(
89 password: &str,
90 cipher: CipherType,
91 salt: &[u8],
92 nonce: &[u8],
93 aad: &[u8],
94 ) -> Result<Self, Error> {
95 (salt.len() == SALT_SIZE && nonce.len() == STREAM_NONCE_SIZE)
96 .then_some(())
97 .ok_or_else(|| Error::InvalidFormat("stream salt or nonce has invalid size".into()))?;
98 let key = Zeroizing::new(derive_key(password, salt, Kdf::Argon2id)?);
99 Ok(Self {
100 cipher,
101 key,
102 nonce: nonce.to_vec(),
103 salt: salt.to_vec(),
104 aad: aad.to_vec(),
105 })
106 }
107
108 #[must_use]
109 pub fn nonce(&self) -> &[u8] {
110 &self.nonce
111 }
112
113 #[must_use]
114 pub fn salt(&self) -> &[u8] {
115 &self.salt
116 }
117
118 pub fn encrypt_chunk(
119 &self,
120 position: u32,
121 kind: ChunkKind,
122 plaintext: &[u8],
123 ) -> Result<Vec<u8>, Error> {
124 let nonce = stream_nonce(&self.nonce, position, kind);
125 crypto_fn(
126 self.cipher,
127 CipherKind::Encrypt,
128 &self.key,
129 &nonce,
130 &self.aad,
131 plaintext,
132 )
133 }
134
135 pub fn decrypt_chunk(
136 &self,
137 position: u32,
138 kind: ChunkKind,
139 chunk: &[u8],
140 ) -> Result<Vec<u8>, Error> {
141 let nonce = stream_nonce(&self.nonce, position, kind);
142 crypto_fn(
143 self.cipher,
144 CipherKind::Decrypt,
145 &self.key,
146 &nonce,
147 &self.aad,
148 chunk,
149 )
150 }
151}
152
153enum CipherKind {
154 Encrypt,
155 Decrypt,
156}
157
158fn crypto_fn(
159 cipher: CipherType,
160 kind: CipherKind,
161 key: &[u8],
162 nonce: &[u8],
163 aad: &[u8],
164 data: &[u8],
165) -> Result<Vec<u8>, Error> {
166 match (cipher, kind) {
167 (CipherType::ChaCha20Poly1305, CipherKind::Encrypt) => {
168 ChaCha20Poly1305::new_from_slice(key)?
169 .encrypt(
170 chacha20poly1305::Nonce::from_slice(nonce),
171 Payload { msg: data, aad },
172 )
173 .map_err(Error::Encrypt)
174 }
175 (CipherType::ChaCha20Poly1305, CipherKind::Decrypt) => {
176 ChaCha20Poly1305::new_from_slice(key)?
177 .decrypt(
178 chacha20poly1305::Nonce::from_slice(nonce),
179 Payload { msg: data, aad },
180 )
181 .map_err(Error::Decrypt)
182 }
183 (CipherType::Aes256Gcm, CipherKind::Encrypt) => Aes256Gcm::new_from_slice(key)?
184 .encrypt(
185 aes_gcm::Nonce::from_slice(nonce),
186 Payload { msg: data, aad },
187 )
188 .map_err(Error::Encrypt),
189 (CipherType::Aes256Gcm, CipherKind::Decrypt) => Aes256Gcm::new_from_slice(key)?
190 .decrypt(
191 aes_gcm::Nonce::from_slice(nonce),
192 Payload { msg: data, aad },
193 )
194 .map_err(Error::Decrypt),
195 }
196}
197
198pub fn stream_encrypt_symmetric(
199 plaintext: &[u8],
200 password: &str,
201 cipher: CipherType,
202 aad: &[u8],
203) -> Result<EncryptedNote, Error> {
204 let parts = StreamParts::derive(password, cipher, aad)?;
205 let ciphertext = (0..plaintext.len())
206 .step_by(STREAM_CHUNK)
207 .enumerate()
208 .map(|(position, offset)| {
209 let end = (offset + STREAM_CHUNK).min(plaintext.len());
210 let kind = if end == plaintext.len() {
211 ChunkKind::Last
212 } else {
213 ChunkKind::NonLast
214 };
215 parts.encrypt_chunk(chunk_position(position)?, kind, &plaintext[offset..end])
216 })
217 .collect::<Result<Vec<_>, _>>()?
218 .into_iter()
219 .flatten()
220 .collect();
221 Ok(EncryptedNote {
222 cipher,
223 nonce: parts.nonce().to_vec(),
224 ciphertext,
225 salt: parts.salt().to_vec(),
226 kdf: Kdf::Argon2id,
227 })
228}
229
230pub fn stream_decrypt_symmetric(
231 data: &EncryptedNote,
232 password: &str,
233 aad: &[u8],
234) -> Result<Vec<u8>, Error> {
235 let parts = StreamParts::recover(password, data.cipher, &data.salt, &data.nonce, aad)?;
236 (0..data.ciphertext.len())
237 .step_by(STREAM_CHUNK + STREAM_TAG)
238 .enumerate()
239 .map(|(position, offset)| {
240 let end = (offset + STREAM_CHUNK + STREAM_TAG).min(data.ciphertext.len());
241 let kind = if end == data.ciphertext.len() {
242 ChunkKind::Last
243 } else {
244 ChunkKind::NonLast
245 };
246 parts.decrypt_chunk(
247 chunk_position(position)?,
248 kind,
249 &data.ciphertext[offset..end],
250 )
251 })
252 .collect::<Result<Vec<_>, _>>()
253 .map(|chunks| chunks.into_iter().flatten().collect())
254}
255
256#[cfg(debug_assertions)]
257fn env_cost(name: &str, default: u32) -> u32 {
258 std::env::var(name)
259 .ok()
260 .and_then(|v| v.parse().ok())
261 .unwrap_or(default)
262}
263
264#[cfg(not(debug_assertions))]
265fn env_cost(_name: &str, default: u32) -> u32 {
266 default
267}
268
269fn kdf_params() -> Result<Params, Error> {
270 Params::new(
271 env_cost("FUNCTORA_KDF_M_COST_KIB", ARGON2_M_COST_KIB),
272 env_cost("FUNCTORA_KDF_T_COST", ARGON2_T_COST),
273 ARGON2_P_COST,
274 Some(KEY_SIZE),
275 )?
276 .pipe(Ok)
277}
278
279pub fn derive_key(password: &str, salt: &[u8], kdf: Kdf) -> Result<Vec<u8>, Error> {
280 let mut key = vec![0u8; KEY_SIZE];
281 match kdf {
282 Kdf::Argon2id => {
283 let params = kdf_params()?;
284 Argon2::new(Argon2Algo, Argon2V, params).hash_password_into(
285 password.as_bytes(),
286 salt,
287 &mut key,
288 )?;
289 }
290 }
291 Ok(key)
292}
293
294fn random_vec(n: usize) -> Result<Vec<u8>, Error> {
295 let mut v = vec![0u8; n];
296 getrandom::getrandom(&mut v)?;
297 Ok(v)
298}
299
300pub fn encrypt_symmetric(
301 plaintext: &[u8],
302 password: &str,
303 cipher: CipherType,
304 aad: &[u8],
305) -> Result<EncryptedNote, Error> {
306 let salt = random_vec(SALT_SIZE)?;
307 let key = Zeroizing::new(derive_key(password, &salt, Kdf::Argon2id)?);
308 let nonce = random_vec(NONCE_SIZE)?;
309
310 let ciphertext = match cipher {
311 CipherType::ChaCha20Poly1305 => {
312 let c = ChaCha20Poly1305::new_from_slice(&key)?;
313 c.encrypt(
314 chacha20poly1305::Nonce::from_slice(&nonce),
315 Payload {
316 msg: plaintext,
317 aad,
318 },
319 )
320 .map_err(Error::Encrypt)?
321 }
322 CipherType::Aes256Gcm => {
323 let c = Aes256Gcm::new_from_slice(&key)?;
324 c.encrypt(
325 aes_gcm::Nonce::from_slice(&nonce),
326 Payload {
327 msg: plaintext,
328 aad,
329 },
330 )
331 .map_err(Error::Encrypt)?
332 }
333 };
334
335 Ok(EncryptedNote {
336 cipher,
337 nonce,
338 ciphertext,
339 salt,
340 kdf: Kdf::Argon2id,
341 })
342}
343
344fn validate_note(data: &EncryptedNote) -> Result<(), Error> {
345 (data.nonce.len() == NONCE_SIZE && data.salt.len() == SALT_SIZE)
346 .then_some(())
347 .ok_or_else(|| Error::InvalidFormat("nonce or salt has invalid size".into()))
348}
349
350pub fn decrypt_symmetric(
351 data: &EncryptedNote,
352 password: &str,
353 aad: &[u8],
354) -> Result<Vec<u8>, Error> {
355 validate_note(data)?;
356 let key = Zeroizing::new(derive_key(password, &data.salt, data.kdf)?);
357
358 match data.cipher {
359 CipherType::ChaCha20Poly1305 => {
360 let c = ChaCha20Poly1305::new_from_slice(&key)?;
361 c.decrypt(
362 chacha20poly1305::Nonce::from_slice(&data.nonce),
363 Payload {
364 msg: &data.ciphertext,
365 aad,
366 },
367 )
368 .map_err(Error::Decrypt)
369 }
370 CipherType::Aes256Gcm => {
371 let c = Aes256Gcm::new_from_slice(&key)?;
372 c.decrypt(
373 aes_gcm::Nonce::from_slice(&data.nonce),
374 Payload {
375 msg: &data.ciphertext,
376 aad,
377 },
378 )
379 .map_err(Error::Decrypt)
380 }
381 }
382}