extern crate alloc;
use alloc::vec::Vec;
use embark_format::CryptoId;
#[cfg(feature = "dec")]
use embark_format::Error;
#[cfg(feature = "aes")]
use crate::Aes256Gcm;
use crate::ChaCha20Poly1305;
#[cfg(feature = "enc")]
#[must_use]
pub fn seal(
crypto: CryptoId,
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
plain: &[u8],
) -> (Vec<u8>, [u8; 16]) {
use crate::Aead;
match crypto {
CryptoId::ChaCha20Poly1305 => ChaCha20Poly1305.seal(key, nonce, aad, plain),
#[cfg(feature = "aes")]
CryptoId::Aes256Gcm => Aes256Gcm.seal(key, nonce, aad, plain),
other => panic!(
"embark-crypt: seal requires a real AEAD cipher, got crypto id {}",
other.as_u8()
),
}
}
#[cfg(feature = "dec")]
pub fn open(
crypto: CryptoId,
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
ct: &[u8],
tag: &[u8; 16],
) -> Result<Vec<u8>, Error> {
use crate::Aead;
match crypto {
CryptoId::ChaCha20Poly1305 => ChaCha20Poly1305.open(key, nonce, aad, ct, tag),
#[cfg(feature = "aes")]
CryptoId::Aes256Gcm => Aes256Gcm.open(key, nonce, aad, ct, tag),
other => Err(Error::UnknownCrypto(other.as_u8())),
}
}
#[cfg(all(test, feature = "enc", feature = "dec"))]
mod tests {
use super::*;
#[test]
fn chacha_dispatch_roundtrip() {
let key = [7u8; 32];
let nonce = [8u8; 12];
let (ct, tag) = seal(CryptoId::ChaCha20Poly1305, &key, &nonce, b"h", b"dispatch");
let got = open(CryptoId::ChaCha20Poly1305, &key, &nonce, b"h", &ct, &tag).unwrap();
assert_eq!(got, b"dispatch");
}
#[cfg(feature = "aes")]
#[test]
fn aes_dispatch_roundtrip() {
let key = [7u8; 32];
let nonce = [8u8; 12];
let (ct, tag) = seal(CryptoId::Aes256Gcm, &key, &nonce, b"h", b"dispatch-aes");
let got = open(CryptoId::Aes256Gcm, &key, &nonce, b"h", &ct, &tag).unwrap();
assert_eq!(got, b"dispatch-aes");
}
#[test]
fn open_unknown_crypto_errors() {
let key = [1u8; 32];
let nonce = [2u8; 12];
let (ct, tag) = seal(CryptoId::ChaCha20Poly1305, &key, &nonce, b"", b"x");
assert_eq!(
open(CryptoId::None, &key, &nonce, b"", &ct, &tag),
Err(embark_format::Error::UnknownCrypto(0))
);
}
}