Skip to main content

functora_core/
crypto.rs

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
198fn chunk_kind(final_chunk: bool) -> ChunkKind {
199    if final_chunk {
200        ChunkKind::Last
201    } else {
202        ChunkKind::NonLast
203    }
204}
205
206pub(crate) fn stream_spans(
207    len: usize,
208    step: usize,
209) -> impl Iterator<Item = Result<(u32, ChunkKind, usize, usize), Error>> {
210    (0..len)
211        .step_by(step)
212        .enumerate()
213        .map(move |(position, offset)| {
214            let end = (offset + step).min(len);
215            chunk_position(position).map(|index| (index, chunk_kind(end == len), offset, end))
216        })
217}
218
219pub fn stream_encrypt_symmetric(
220    plaintext: &[u8],
221    password: &str,
222    cipher: CipherType,
223    aad: &[u8],
224) -> Result<EncryptedNote, Error> {
225    let parts = StreamParts::derive(password, cipher, aad)?;
226    stream_spans(plaintext.len(), STREAM_CHUNK)
227        .map(|span| {
228            let (position, kind, offset, end) = span?;
229            parts.encrypt_chunk(position, kind, &plaintext[offset..end])
230        })
231        .collect::<Result<Vec<_>, _>>()?
232        .into_iter()
233        .flatten()
234        .collect::<Vec<u8>>()
235        .pipe(|ciphertext| {
236            Ok(EncryptedNote {
237                cipher,
238                nonce: parts.nonce().to_vec(),
239                ciphertext,
240                salt: parts.salt().to_vec(),
241                kdf: Kdf::Argon2id,
242            })
243        })
244}
245
246pub fn stream_decrypt_symmetric(
247    data: &EncryptedNote,
248    password: &str,
249    aad: &[u8],
250) -> Result<Vec<u8>, Error> {
251    let parts = StreamParts::recover(password, data.cipher, &data.salt, &data.nonce, aad)?;
252    stream_spans(data.ciphertext.len(), STREAM_CHUNK + STREAM_TAG)
253        .map(|span| {
254            let (position, kind, offset, end) = span?;
255            parts.decrypt_chunk(position, kind, &data.ciphertext[offset..end])
256        })
257        .collect::<Result<Vec<_>, _>>()
258        .map(|chunks| chunks.into_iter().flatten().collect())
259}
260
261#[cfg(debug_assertions)]
262fn env_cost(name: &str, default: u32) -> u32 {
263    std::env::var(name)
264        .ok()
265        .and_then(|v| v.parse().ok())
266        .unwrap_or(default)
267}
268
269#[cfg(not(debug_assertions))]
270fn env_cost(_name: &str, default: u32) -> u32 {
271    default
272}
273
274fn kdf_params() -> Result<Params, Error> {
275    Params::new(
276        env_cost("FUNCTORA_KDF_M_COST_KIB", ARGON2_M_COST_KIB),
277        env_cost("FUNCTORA_KDF_T_COST", ARGON2_T_COST),
278        ARGON2_P_COST,
279        Some(KEY_SIZE),
280    )?
281    .pipe(Ok)
282}
283
284pub fn derive_key(password: &str, salt: &[u8], kdf: Kdf) -> Result<Vec<u8>, Error> {
285    let mut key = vec![0u8; KEY_SIZE];
286    match kdf {
287        Kdf::Argon2id => {
288            let params = kdf_params()?;
289            Argon2::new(Argon2Algo, Argon2V, params).hash_password_into(
290                password.as_bytes(),
291                salt,
292                &mut key,
293            )?;
294        }
295    }
296    Ok(key)
297}
298
299fn random_vec(n: usize) -> Result<Vec<u8>, Error> {
300    let mut v = vec![0u8; n];
301    getrandom::getrandom(&mut v)?;
302    Ok(v)
303}
304
305pub fn encrypt_symmetric(
306    plaintext: &[u8],
307    password: &str,
308    cipher: CipherType,
309    aad: &[u8],
310) -> Result<EncryptedNote, Error> {
311    let salt = random_vec(SALT_SIZE)?;
312    let key = Zeroizing::new(derive_key(password, &salt, Kdf::Argon2id)?);
313    let nonce = random_vec(NONCE_SIZE)?;
314
315    let ciphertext = match cipher {
316        CipherType::ChaCha20Poly1305 => {
317            let c = ChaCha20Poly1305::new_from_slice(&key)?;
318            c.encrypt(
319                chacha20poly1305::Nonce::from_slice(&nonce),
320                Payload {
321                    msg: plaintext,
322                    aad,
323                },
324            )
325            .map_err(Error::Encrypt)?
326        }
327        CipherType::Aes256Gcm => {
328            let c = Aes256Gcm::new_from_slice(&key)?;
329            c.encrypt(
330                aes_gcm::Nonce::from_slice(&nonce),
331                Payload {
332                    msg: plaintext,
333                    aad,
334                },
335            )
336            .map_err(Error::Encrypt)?
337        }
338    };
339
340    Ok(EncryptedNote {
341        cipher,
342        nonce,
343        ciphertext,
344        salt,
345        kdf: Kdf::Argon2id,
346    })
347}
348
349fn validate_note(data: &EncryptedNote) -> Result<(), Error> {
350    (data.nonce.len() == NONCE_SIZE && data.salt.len() == SALT_SIZE)
351        .then_some(())
352        .ok_or_else(|| Error::InvalidFormat("nonce or salt has invalid size".into()))
353}
354
355pub fn decrypt_symmetric(
356    data: &EncryptedNote,
357    password: &str,
358    aad: &[u8],
359) -> Result<Vec<u8>, Error> {
360    validate_note(data)?;
361    let key = Zeroizing::new(derive_key(password, &data.salt, data.kdf)?);
362
363    match data.cipher {
364        CipherType::ChaCha20Poly1305 => {
365            let c = ChaCha20Poly1305::new_from_slice(&key)?;
366            c.decrypt(
367                chacha20poly1305::Nonce::from_slice(&data.nonce),
368                Payload {
369                    msg: &data.ciphertext,
370                    aad,
371                },
372            )
373            .map_err(Error::Decrypt)
374        }
375        CipherType::Aes256Gcm => {
376            let c = Aes256Gcm::new_from_slice(&key)?;
377            c.decrypt(
378                aes_gcm::Nonce::from_slice(&data.nonce),
379                Payload {
380                    msg: &data.ciphertext,
381                    aad,
382                },
383            )
384            .map_err(Error::Decrypt)
385        }
386    }
387}