use crate::CryptoError;
pub(crate) const KEY_SIZE: usize = 32;
pub(crate) const NONCE_SIZE: usize = 12;
pub(crate) const VERSION: u8 = 0x01;
pub(crate) const DEFAULT_CONTEXT: &str = "encryptman-v1";
pub(crate) const MIN_PACKED_SIZE: usize = 1 + NONCE_SIZE + 1;
pub(crate) fn pack(nonce: &[u8; NONCE_SIZE], ciphertext: &[u8]) -> Vec<u8> {
let mut packed = Vec::with_capacity(1 + NONCE_SIZE + ciphertext.len());
packed.push(VERSION);
packed.extend_from_slice(nonce);
packed.extend_from_slice(ciphertext);
packed
}
pub(crate) fn unpack(packed: &[u8]) -> Result<(&[u8; NONCE_SIZE], &[u8]), CryptoError> {
if packed.len() < MIN_PACKED_SIZE {
return Err(CryptoError::CiphertextTooShort {
expected: MIN_PACKED_SIZE,
actual: packed.len(),
});
}
let (version, rest) = packed
.split_first()
.ok_or(CryptoError::CiphertextTooShort {
expected: MIN_PACKED_SIZE,
actual: packed.len(),
})?;
if *version != VERSION {
return Err(CryptoError::UnsupportedVersion(*version));
}
let (nonce, ciphertext) = rest.split_at(NONCE_SIZE);
let nonce = nonce
.try_into()
.map_err(|_| CryptoError::CiphertextTooShort {
expected: MIN_PACKED_SIZE,
actual: packed.len(),
})?;
Ok((nonce, ciphertext))
}