lum_ccc_rust/crates/ccc-crypto-rustcrypto/src/aead.rs

240 lines
7.9 KiB
Rust

//! AEAD implementations from the RustCrypto `aead` 0.6 family.
//!
//! Wire format matches the wolfSSL provider: `ciphertext || 16-byte tag`.
//!
//! | Algorithm | Crate |
//! |--------------------|-----------------------|
//! | AES-256-GCM | `aes-gcm` |
//! | AES-256-GCM-SIV | `aes-gcm-siv` |
//! | ChaCha20-Poly1305 | `chacha20poly1305` |
//! | XChaCha20-Poly1305 | `chacha20poly1305` |
//! | Ascon-AEAD128 | `ascon-aead` (SP 800-232) |
//!
//! The pre-standard Ascon-128a (ID 15) is not offered: `ascon-aead` 0.6
//! implements only the final NIST SP 800-232 Ascon-AEAD128, which is a
//! different algorithm, so ID 15 returns [`CryptoError::FeatureNotCompiled`].
use aes_gcm::aead::{Aead, KeyInit, Nonce, Payload};
use aes_gcm::Aes256Gcm;
use aes_gcm_siv::Aes256GcmSiv;
use ascon_aead::AsconAead128;
use chacha20poly1305::{ChaCha20Poly1305, XChaCha20Poly1305};
use ccc_crypto_core::{algorithms::AeadAlgorithm, error::CryptoError};
const TAG_LEN: usize = 16;
/// Encrypt `plaintext`; returns `ciphertext || tag`.
pub fn encrypt(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
validate_key_nonce(algo, key, nonce)?;
match algo {
AeadAlgorithm::AesGcm256 => seal::<Aes256Gcm>(algo, key, nonce, plaintext, aad),
AeadAlgorithm::AesGcmSiv256 => seal::<Aes256GcmSiv>(algo, key, nonce, plaintext, aad),
AeadAlgorithm::ChaCha20Poly1305 => {
seal::<ChaCha20Poly1305>(algo, key, nonce, plaintext, aad)
}
AeadAlgorithm::XChaCha20Poly1305 => {
seal::<XChaCha20Poly1305>(algo, key, nonce, plaintext, aad)
}
AeadAlgorithm::AsconAead128 => seal::<AsconAead128>(algo, key, nonce, plaintext, aad),
AeadAlgorithm::Ascon128a => Err(CryptoError::FeatureNotCompiled(algo.name().into())),
}
}
/// Authenticate and decrypt `ciphertext || tag`.
///
/// Returns [`CryptoError::AuthenticationFailed`] if the tag does not verify.
pub fn decrypt(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
validate_key_nonce(algo, key, nonce)?;
if ciphertext_and_tag.len() < TAG_LEN {
return Err(CryptoError::InvalidInput(format!(
"{}: ciphertext too short (no room for tag)",
algo.name()
)));
}
let ct = ciphertext_and_tag;
match algo {
AeadAlgorithm::AesGcm256 => open::<Aes256Gcm>(algo, key, nonce, ct, aad),
AeadAlgorithm::AesGcmSiv256 => open::<Aes256GcmSiv>(algo, key, nonce, ct, aad),
AeadAlgorithm::ChaCha20Poly1305 => open::<ChaCha20Poly1305>(algo, key, nonce, ct, aad),
AeadAlgorithm::XChaCha20Poly1305 => open::<XChaCha20Poly1305>(algo, key, nonce, ct, aad),
AeadAlgorithm::AsconAead128 => open::<AsconAead128>(algo, key, nonce, ct, aad),
AeadAlgorithm::Ascon128a => Err(CryptoError::FeatureNotCompiled(algo.name().into())),
}
}
fn validate_key_nonce(algo: AeadAlgorithm, key: &[u8], nonce: &[u8]) -> Result<(), CryptoError> {
if key.len() != algo.key_len() {
return Err(CryptoError::InvalidKey(format!(
"{}: expected {}-byte key, got {}",
algo.name(),
algo.key_len(),
key.len()
)));
}
if nonce.len() != algo.nonce_len() {
return Err(CryptoError::InvalidNonce(format!(
"{}: expected {}-byte nonce, got {}",
algo.name(),
algo.nonce_len(),
nonce.len()
)));
}
Ok(())
}
fn cipher<C: KeyInit>(algo: AeadAlgorithm, key: &[u8]) -> Result<C, CryptoError> {
C::new_from_slice(key).map_err(|_| CryptoError::InvalidKey(algo.name().into()))
}
fn nonce_of<C: Aead>(algo: AeadAlgorithm, nonce: &[u8]) -> Result<Nonce<C>, CryptoError> {
Nonce::<C>::try_from(nonce).map_err(|_| CryptoError::InvalidNonce(algo.name().into()))
}
fn seal<C: KeyInit + Aead>(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
let c = cipher::<C>(algo, key)?;
let n = nonce_of::<C>(algo, nonce)?;
c.encrypt(
&n,
Payload {
msg: plaintext,
aad,
},
)
.map_err(|_| CryptoError::InvalidInput(format!("{}: input too long", algo.name())))
}
fn open<C: KeyInit + Aead>(
algo: AeadAlgorithm,
key: &[u8],
nonce: &[u8],
ciphertext_and_tag: &[u8],
aad: &[u8],
) -> Result<Vec<u8>, CryptoError> {
let c = cipher::<C>(algo, key)?;
let n = nonce_of::<C>(algo, nonce)?;
c.decrypt(
&n,
Payload {
msg: ciphertext_and_tag,
aad,
},
)
.map_err(|_| CryptoError::AuthenticationFailed)
}
#[cfg(test)]
mod tests {
use super::*;
const OFFERED: [AeadAlgorithm; 5] = [
AeadAlgorithm::AesGcm256,
AeadAlgorithm::AesGcmSiv256,
AeadAlgorithm::ChaCha20Poly1305,
AeadAlgorithm::XChaCha20Poly1305,
AeadAlgorithm::AsconAead128,
];
fn inputs(algo: AeadAlgorithm) -> (Vec<u8>, Vec<u8>) {
let key = (0..algo.key_len() as u8).collect();
let nonce = (0..algo.nonce_len() as u8).map(|b| b ^ 0x5a).collect();
(key, nonce)
}
#[test]
fn roundtrip_all_offered() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
for (pt, aad) in [
(&b"hello cascade"[..], &b"hdr"[..]),
(b"", b""),
(b"x", b""),
(b"", b"aad only"),
] {
let ct = encrypt(algo, &key, &nonce, pt, aad).unwrap();
assert_eq!(ct.len(), pt.len() + TAG_LEN, "{}", algo.name());
assert_eq!(decrypt(algo, &key, &nonce, &ct, aad).unwrap(), pt);
}
}
}
#[test]
fn tampering_is_rejected() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
let ct = encrypt(algo, &key, &nonce, b"payload", b"aad").unwrap();
for i in [0, ct.len() - 1] {
let mut bad = ct.clone();
bad[i] ^= 0x01;
assert!(matches!(
decrypt(algo, &key, &nonce, &bad, b"aad"),
Err(CryptoError::AuthenticationFailed)
));
}
assert!(matches!(
decrypt(algo, &key, &nonce, &ct, b"aaD"),
Err(CryptoError::AuthenticationFailed)
));
}
}
#[test]
fn bad_lengths_are_rejected() {
for algo in OFFERED {
let (key, nonce) = inputs(algo);
assert!(matches!(
encrypt(algo, &key[1..], &nonce, b"", b""),
Err(CryptoError::InvalidKey(_))
));
assert!(matches!(
encrypt(algo, &key, &nonce[1..], b"", b""),
Err(CryptoError::InvalidNonce(_))
));
assert!(matches!(
decrypt(algo, &key, &nonce, &[0u8; 15], b""),
Err(CryptoError::InvalidInput(_))
));
}
}
#[test]
fn ascon128a_is_not_compiled() {
let key = [0u8; 16];
let nonce = [0u8; 16];
assert!(matches!(
encrypt(AeadAlgorithm::Ascon128a, &key, &nonce, b"", b""),
Err(CryptoError::FeatureNotCompiled(_))
));
}
#[test]
fn algorithms_are_not_interchangeable() {
let key = [7u8; 32];
let nonce = [9u8; 12];
let gcm = encrypt(AeadAlgorithm::AesGcm256, &key, &nonce, b"same", b"").unwrap();
let siv = encrypt(AeadAlgorithm::AesGcmSiv256, &key, &nonce, b"same", b"").unwrap();
let cha = encrypt(AeadAlgorithm::ChaCha20Poly1305, &key, &nonce, b"same", b"").unwrap();
assert_ne!(gcm, siv);
assert_ne!(gcm, cha);
assert!(decrypt(AeadAlgorithm::AesGcmSiv256, &key, &nonce, &gcm, b"").is_err());
}
}