#[cfg(feature = "dec")]
use embark_format::Error;
extern crate alloc;
use alloc::vec::Vec;
use aes_gcm::Aes256Gcm;
use aes_gcm::aead::{AeadInOut, KeyInit};
#[cfg(feature = "enc")]
pub(crate) fn seal(
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
plain: &[u8],
) -> (Vec<u8>, [u8; 16]) {
let cipher = Aes256Gcm::new(key.into());
let mut buf = plain.to_vec();
let tag = cipher
.encrypt_inout_detached(nonce.into(), aad, buf.as_mut_slice().into())
.expect("embark-crypt: plaintext exceeds the 64 GiB AES-256-GCM message limit");
(buf, tag.into())
}
#[cfg(feature = "dec")]
pub(crate) fn open(
key: &[u8; 32],
nonce: &[u8; 12],
aad: &[u8],
ct: &[u8],
tag: &[u8; 16],
) -> Result<Vec<u8>, Error> {
let cipher = Aes256Gcm::new(key.into());
let mut buf = ct.to_vec();
cipher
.decrypt_inout_detached(nonce.into(), aad, buf.as_mut_slice().into(), tag.into())
.map_err(|_| Error::Auth)?;
Ok(buf)
}
#[cfg(all(test, feature = "enc", feature = "dec"))]
mod tests {
use super::*;
#[test]
fn matches_the_bytes_this_crate_has_always_produced() {
let (ct, tag) = seal(
&[0x42u8; 32],
&[0x24u8; 12],
b"",
b"embark encrypted payload",
);
let hex = |b: &[u8]| {
b.iter()
.map(|x| alloc::format!("{x:02x}"))
.collect::<alloc::string::String>()
};
assert_eq!(
hex(&ct),
"70fca6209bade65b488b50d3cd46f6c24c8b5209dac43109",
"AES-256-GCM ciphertext moved"
);
let (ct_aad, tag_aad) = seal(
&[0x42u8; 32],
&[0x24u8; 12],
b"hdr",
b"embark encrypted payload",
);
assert_eq!(ct_aad, ct);
assert_ne!(tag_aad, tag);
assert_eq!(
hex(&tag),
"a6cd18a896534f2a62a66ce6a4687d8b",
"AES-256-GCM tag moved"
);
}
#[test]
fn roundtrip() {
let key = [0x42u8; 32];
let nonce = [0x24u8; 12];
let plain = b"embark encrypted payload";
let (ct, tag) = seal(&key, &nonce, b"", plain);
assert_ne!(&ct[..], &plain[..]);
let got = open(&key, &nonce, b"", &ct, &tag).unwrap();
assert_eq!(got, plain);
}
#[test]
fn wrong_key_is_auth_error() {
let (ct, tag) = seal(&[1u8; 32], &[2u8; 12], b"", b"secret");
assert_eq!(
open(&[9u8; 32], &[2u8; 12], b"", &ct, &tag),
Err(embark_format::Error::Auth)
);
}
#[test]
fn tampered_ciphertext_is_auth_error() {
let (mut ct, tag) = seal(&[1u8; 32], &[2u8; 12], b"", b"secret");
ct[0] ^= 0xff;
assert_eq!(
open(&[1u8; 32], &[2u8; 12], b"", &ct, &tag),
Err(embark_format::Error::Auth)
);
}
}