use super::kdf::Key;
use crate::{Error, Result};
use alloc::vec::Vec;
use chacha20poly1305::aead::{Aead, KeyInit};
use chacha20poly1305::{ChaCha20Poly1305, Nonce};
pub const SALT_LEN: usize = 16;
pub const NONCE_LEN: usize = 12;
pub const TAG_LEN: usize = 16;
pub fn encrypt_body(key: &Key, nonce: &[u8; NONCE_LEN], plaintext: &[u8]) -> Result<Vec<u8>> {
let cipher = ChaCha20Poly1305::new_from_slice(key)
.map_err(|e| Error::Compression(format!("aead key: {e}")))?;
let n = Nonce::from_slice(nonce);
cipher
.encrypt(n, plaintext)
.map_err(|_| Error::Compression("aead encrypt failed".into()))
}
pub fn decrypt_body(key: &Key, nonce: &[u8; NONCE_LEN], ciphertext: &[u8]) -> Result<Vec<u8>> {
if ciphertext.len() < TAG_LEN {
return Err(Error::Decompression("aead ciphertext too short".into()));
}
let cipher = ChaCha20Poly1305::new_from_slice(key)
.map_err(|e| Error::Decompression(format!("aead key: {e}")))?;
let n = Nonce::from_slice(nonce);
cipher
.decrypt(n, ciphertext)
.map_err(|_| Error::Decompression("aead auth failed (wrong key or corrupt)".into()))
}
pub fn fill_random(buf: &mut [u8]) -> Result<()> {
getrandom::getrandom(buf).map_err(|e| Error::Compression(format!("getrandom: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::crypto::kdf::derive_key_from_password;
#[test]
fn roundtrip() {
let key = derive_key_from_password("pw", b"0123456789abcdef").unwrap();
let mut nonce = [0u8; NONCE_LEN];
fill_random(&mut nonce).unwrap();
let pt = b"hello encrypted zex body";
let ct = encrypt_body(&key, &nonce, pt).unwrap();
assert_ne!(&ct[..pt.len().min(ct.len())], &pt[..]);
let out = decrypt_body(&key, &nonce, &ct).unwrap();
assert_eq!(out, pt);
}
#[test]
fn bad_key_fails() {
let key = derive_key_from_password("pw", b"0123456789abcdef").unwrap();
let mut nonce = [0u8; 12];
fill_random(&mut nonce).unwrap();
let ct = encrypt_body(&key, &nonce, b"data").unwrap();
let bad = [9u8; 32];
assert!(decrypt_body(&bad, &nonce, &ct).is_err());
}
}