extern crate alloc;
#[cfg(any(feature = "enc", feature = "dec"))]
use alloc::vec::Vec;
#[cfg(feature = "dec")]
use embark_format::Error;
mod sealed {
pub trait Sealed {}
}
pub trait Aead: sealed::Sealed {
#[cfg(feature = "enc")]
fn seal(
&self,
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
plain: &[u8],
) -> (Vec<u8>, [u8; 16]);
#[cfg(feature = "dec")]
fn open(
&self,
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
ct: &[u8],
tag: &[u8; 16],
) -> Result<Vec<u8>, Error>;
}
#[derive(Debug)]
pub struct ChaCha20Poly1305;
impl sealed::Sealed for ChaCha20Poly1305 {}
impl Aead for ChaCha20Poly1305 {
#[cfg(feature = "enc")]
fn seal(
&self,
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
plain: &[u8],
) -> (Vec<u8>, [u8; 16]) {
crate::aead::seal(key, nonce, aad, plain)
}
#[cfg(feature = "dec")]
fn open(
&self,
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
ct: &[u8],
tag: &[u8; 16],
) -> Result<Vec<u8>, Error> {
crate::aead::open(key, nonce, aad, ct, tag)
}
}
#[cfg(feature = "aes")]
#[derive(Debug)]
pub struct Aes256Gcm;
#[cfg(feature = "aes")]
impl sealed::Sealed for Aes256Gcm {}
#[cfg(feature = "aes")]
impl Aead for Aes256Gcm {
#[cfg(feature = "enc")]
fn seal(
&self,
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
plain: &[u8],
) -> (Vec<u8>, [u8; 16]) {
crate::aes::seal(key, nonce, aad, plain)
}
#[cfg(feature = "dec")]
fn open(
&self,
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
ct: &[u8],
tag: &[u8; 16],
) -> Result<Vec<u8>, Error> {
crate::aes::open(key, nonce, aad, ct, tag)
}
}
#[cfg(all(test, feature = "enc", feature = "dec"))]
mod tests {
use super::*;
#[test]
fn roundtrips_via_trait() {
let key = [0x11u8; 32];
let nonce = [0x22u8; 12];
let plain = b"trait roundtrip via ChaCha20Poly1305";
let (ct, tag) = ChaCha20Poly1305.seal(&key, &nonce, b"hdr", plain);
assert_ne!(&ct[..], &plain[..]);
let got = ChaCha20Poly1305
.open(&key, &nonce, b"hdr", &ct, &tag)
.unwrap();
assert_eq!(got, plain);
assert_eq!(
ChaCha20Poly1305.open(&key, &nonce, b"HDR", &ct, &tag),
Err(Error::Auth)
);
}
#[cfg(feature = "aes")]
#[test]
fn roundtrips_via_trait_aes() {
let key = [0x11u8; 32];
let nonce = [0x22u8; 12];
let plain = b"trait roundtrip via Aes256Gcm";
let (ct, tag) = Aes256Gcm.seal(&key, &nonce, b"hdr", plain);
assert_ne!(&ct[..], &plain[..]);
let got = Aes256Gcm.open(&key, &nonce, b"hdr", &ct, &tag).unwrap();
assert_eq!(got, plain);
assert_eq!(
Aes256Gcm.open(&key, &nonce, b"HDR", &ct, &tag),
Err(Error::Auth)
);
}
}