use aes_gcm::Aes256Gcm;
use chacha20poly1305::XChaCha20Poly1305;
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use zeroize::Zeroizing;
use crate::format::{self, Kind, VERSION_2};
use crate::{Error, Result, Rng};
pub const KEY_LEN: usize = 32;
pub const TAG_LEN: usize = 16;
pub const XCHACHA_NONCE_LEN: usize = 24;
pub const AES_GCM_NONCE_LEN: usize = 12;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum Algorithm {
#[default]
XChaCha20Poly1305 = 0x01,
Aes256Gcm = 0x02,
}
impl Algorithm {
pub fn from_name(name: &str) -> Result<Self> {
match name.to_ascii_lowercase().replace(['-', '_'], "").as_str() {
"xchacha20poly1305" | "xchacha" => Ok(Self::XChaCha20Poly1305),
"aes256gcm" | "aesgcm" => Ok(Self::Aes256Gcm),
_ => Err(Error::InvalidParams("unknown AEAD algorithm")),
}
}
#[must_use]
pub fn name(self) -> &'static str {
match self {
Self::XChaCha20Poly1305 => "xchacha20poly1305",
Self::Aes256Gcm => "aes256gcm",
}
}
#[must_use]
pub fn nonce_len(self) -> usize {
match self {
Self::XChaCha20Poly1305 => XCHACHA_NONCE_LEN,
Self::Aes256Gcm => AES_GCM_NONCE_LEN,
}
}
pub fn from_id(id: u8) -> Result<Self> {
match id {
0x01 => Ok(Self::XChaCha20Poly1305),
0x02 => Ok(Self::Aes256Gcm),
other => Err(Error::UnknownSuite(other)),
}
}
}
pub fn generate_key<R: Rng + ?Sized>(rng: &mut R) -> Zeroizing<[u8; KEY_LEN]> {
Zeroizing::new(crate::random(rng))
}
fn key32(key: &[u8]) -> Result<&[u8; KEY_LEN]> {
key.try_into().map_err(|_| Error::InvalidLength("AEAD key"))
}
pub fn encrypt<R: Rng + ?Sized>(
alg: Algorithm,
key: &[u8],
plaintext: &[u8],
aad: &[u8],
rng: &mut R,
) -> Result<Vec<u8>> {
let key = key32(key)?;
let header = format::Header::current(Kind::AeadCiphertext, alg as u8).to_bytes();
let mut nonce = vec![0u8; alg.nonce_len()];
rng.fill_bytes(&mut nonce);
let full_aad = [&header[..], aad].concat();
let ct = encrypt_raw(alg, key, &nonce, &full_aad, plaintext)?;
Ok([&header[..], &nonce, &ct].concat())
}
pub fn decrypt(key: &[u8], data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
let key = key32(key)?;
let (h, body) = format::expect(data, Kind::AeadCiphertext)?;
let alg = Algorithm::from_id(h.suite)?;
match h.version {
VERSION_2 => {
if body.len() < alg.nonce_len() + TAG_LEN {
return Err(Error::InvalidLength("AEAD ciphertext"));
}
let (nonce, ct) = format::take(body, alg.nonce_len(), "AEAD ciphertext")?;
let full_aad = [&h.to_bytes()[..], aad].concat();
decrypt_raw(alg, key, nonce, &full_aad, ct)
}
v => Err(Error::UnsupportedVersion(v)),
}
}
pub fn encrypt_raw(alg: Algorithm, key: &[u8; KEY_LEN], nonce: &[u8], aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>> {
if nonce.len() != alg.nonce_len() {
return Err(Error::InvalidLength("AEAD nonce"));
}
let payload = Payload { msg: plaintext, aad };
let out = match alg {
Algorithm::XChaCha20Poly1305 => {
let n: [u8; XCHACHA_NONCE_LEN] = nonce.try_into().map_err(|_| Error::InvalidLength("AEAD nonce"))?;
XChaCha20Poly1305::new(key.into()).encrypt(&n.into(), payload)
}
Algorithm::Aes256Gcm => {
let n: [u8; AES_GCM_NONCE_LEN] = nonce.try_into().map_err(|_| Error::InvalidLength("AEAD nonce"))?;
Aes256Gcm::new(key.into()).encrypt(&n.into(), payload)
}
};
out.map_err(|_| Error::InvalidParams("plaintext too long"))
}
pub fn decrypt_raw(
alg: Algorithm,
key: &[u8; KEY_LEN],
nonce: &[u8],
aad: &[u8],
ciphertext: &[u8],
) -> Result<Zeroizing<Vec<u8>>> {
if nonce.len() != alg.nonce_len() {
return Err(Error::InvalidLength("AEAD nonce"));
}
let payload = Payload { msg: ciphertext, aad };
let out = match alg {
Algorithm::XChaCha20Poly1305 => {
let n: [u8; XCHACHA_NONCE_LEN] = nonce.try_into().map_err(|_| Error::InvalidLength("AEAD nonce"))?;
XChaCha20Poly1305::new(key.into()).decrypt(&n.into(), payload)
}
Algorithm::Aes256Gcm => {
let n: [u8; AES_GCM_NONCE_LEN] = nonce.try_into().map_err(|_| Error::InvalidLength("AEAD nonce"))?;
Aes256Gcm::new(key.into()).decrypt(&n.into(), payload)
}
};
out.map(Zeroizing::new).map_err(|_| Error::Decrypt)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::format::HEADER_LEN;
use crate::test_util::rng;
const ALGS: [Algorithm; 2] = [Algorithm::XChaCha20Poly1305, Algorithm::Aes256Gcm];
#[test]
fn round_trip() {
let mut rng = rng();
for alg in ALGS {
let key = generate_key(&mut rng);
let ct = encrypt(alg, &key[..], b"hello", b"aad", &mut rng).unwrap();
assert_eq!(ct.len(), HEADER_LEN + alg.nonce_len() + 5 + TAG_LEN);
assert_eq!(*decrypt(&key[..], &ct, b"aad").unwrap(), b"hello");
assert_eq!(Algorithm::from_name(alg.name()).unwrap(), alg);
assert_eq!(Algorithm::from_id(alg as u8).unwrap(), alg);
}
}
#[test]
fn tamper_and_wrong_key_fail() {
let mut rng = rng();
for alg in ALGS {
let key = generate_key(&mut rng);
let other = generate_key(&mut rng);
let ct = encrypt(alg, &key[..], b"hello", b"aad", &mut rng).unwrap();
assert_eq!(decrypt(&other[..], &ct, b"aad"), Err(Error::Decrypt));
assert_eq!(decrypt(&key[..], &ct, b"other"), Err(Error::Decrypt));
for i in HEADER_LEN..ct.len() {
let mut t = ct.clone();
t[i] ^= 0x01;
assert_eq!(decrypt(&key[..], &t, b"aad"), Err(Error::Decrypt), "byte {i}");
}
assert_eq!(
decrypt(&key[..], &ct[..HEADER_LEN + 3], b"aad"),
Err(Error::InvalidLength("AEAD ciphertext"))
);
}
}
#[test]
fn header_is_authenticated() {
let mut rng = rng();
let key = generate_key(&mut rng);
let mut ct = encrypt(Algorithm::Aes256Gcm, &key[..], b"hello", b"", &mut rng).unwrap();
ct[5] = Algorithm::XChaCha20Poly1305 as u8;
assert!(decrypt(&key[..], &ct, b"").is_err());
ct[5] = 0x07;
assert_eq!(decrypt(&key[..], &ct, b""), Err(Error::UnknownSuite(7)));
}
#[test]
fn rejects_bad_key_length() {
let mut rng = rng();
assert_eq!(
encrypt(Algorithm::default(), &[0u8; 16], b"", b"", &mut rng),
Err(Error::InvalidLength("AEAD key"))
);
}
}