use crate::error::Result;
pub mod aes;
pub mod chacha;
pub trait Cipher {
type Key;
type Nonce;
const TAG_SIZE: usize;
fn encrypted_size(plaintext_len: usize) -> usize {
plaintext_len + Self::TAG_SIZE
}
fn decrypted_size(ciphertext_len: usize) -> Option<usize> {
ciphertext_len.checked_sub(Self::TAG_SIZE)
}
fn encrypt(key: &Self::Key, nonce: &Self::Nonce, plaintext: &[u8]) -> Result<Vec<u8>> {
let mut ciphertext = vec![0u8; Self::encrypted_size(plaintext.len())];
let len = Self::encrypt_to(key, nonce, plaintext, &mut ciphertext)?;
ciphertext.truncate(len);
Ok(ciphertext)
}
fn encrypt_to(
key: &Self::Key,
nonce: &Self::Nonce,
plaintext: &[u8],
ciphertext: &mut [u8],
) -> Result<usize>;
fn decrypt(key: &Self::Key, nonce: &Self::Nonce, ciphertext: &[u8]) -> Result<Vec<u8>> {
let mut plaintext = vec![0u8; ciphertext.len()];
let len = Self::decrypt_to(key, nonce, ciphertext, &mut plaintext)?;
plaintext.truncate(len);
Ok(plaintext)
}
fn decrypt_to(
key: &Self::Key,
nonce: &Self::Nonce,
ciphertext: &[u8],
plaintext: &mut [u8],
) -> Result<usize>;
}
pub trait AuthenticatedCipher {
type Key;
type Nonce;
const TAG_SIZE: usize;
fn sealed_size(plaintext_len: usize) -> usize {
plaintext_len + Self::TAG_SIZE
}
fn opened_size(ciphertext_len: usize) -> Option<usize> {
ciphertext_len.checked_sub(Self::TAG_SIZE)
}
fn seal(key: &Self::Key, nonce: &Self::Nonce, plaintext: &[u8]) -> Result<Vec<u8>> {
let mut ciphertext = vec![0u8; Self::sealed_size(plaintext.len())];
let len = Self::seal_to(key, nonce, plaintext, &mut ciphertext)?;
ciphertext.truncate(len);
Ok(ciphertext)
}
fn seal_to(
key: &Self::Key,
nonce: &Self::Nonce,
plaintext: &[u8],
ciphertext: &mut [u8],
) -> Result<usize>;
fn open(key: &Self::Key, nonce: &Self::Nonce, ciphertext: &[u8]) -> Result<Vec<u8>> {
let mut plaintext = vec![0u8; ciphertext.len()];
let len = Self::open_to(key, nonce, ciphertext, &mut plaintext)?;
plaintext.truncate(len);
Ok(plaintext)
}
fn open_to(
key: &Self::Key,
nonce: &Self::Nonce,
ciphertext: &[u8],
plaintext: &mut [u8],
) -> Result<usize>;
fn seal_with_aad(
key: &Self::Key,
nonce: &Self::Nonce,
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>> {
let mut ciphertext = vec![0u8; Self::sealed_size(plaintext.len())];
let len = Self::seal_to_with_aad(key, nonce, plaintext, aad, &mut ciphertext)?;
ciphertext.truncate(len);
Ok(ciphertext)
}
fn seal_to_with_aad(
key: &Self::Key,
nonce: &Self::Nonce,
plaintext: &[u8],
aad: &[u8],
ciphertext: &mut [u8],
) -> Result<usize>;
fn open_with_aad(
key: &Self::Key,
nonce: &Self::Nonce,
ciphertext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>> {
let mut plaintext = vec![0u8; ciphertext.len()];
let len = Self::open_to_with_aad(key, nonce, ciphertext, aad, &mut plaintext)?;
plaintext.truncate(len);
Ok(plaintext)
}
fn open_to_with_aad(
key: &Self::Key,
nonce: &Self::Nonce,
ciphertext: &[u8],
aad: &[u8],
plaintext: &mut [u8],
) -> Result<usize>;
}