use chacha20poly1305::{
aead::{Aead, Payload},
KeyInit,
};
use tink_core::{utils::wrap_err, TinkError};
pub const CHA_CHA20_KEY_SIZE: usize = 32;
pub const CHA_CHA20_NONCE_SIZE: usize = 12;
const POLY1305_TAG_SIZE: usize = 16;
#[derive(Clone)]
pub struct ChaCha20Poly1305 {
key: chacha20poly1305::Key,
}
impl ChaCha20Poly1305 {
pub fn new(key: &[u8]) -> Result<ChaCha20Poly1305, TinkError> {
if key.len() != CHA_CHA20_KEY_SIZE {
return Err("ChaCha20Poly1305: bad key length".into());
}
Ok(ChaCha20Poly1305 {
key: chacha20poly1305::Key::clone_from_slice(key),
})
}
}
impl tink_core::Aead for ChaCha20Poly1305 {
fn encrypt(&self, pt: &[u8], aad: &[u8]) -> Result<Vec<u8>, TinkError> {
if pt.len() > (isize::MAX as usize) - CHA_CHA20_NONCE_SIZE - POLY1305_TAG_SIZE {
return Err("ChaCha20Poly1305: plaintext too long".into());
}
let cipher = chacha20poly1305::ChaCha20Poly1305::new(&self.key);
let n = new_nonce();
let ct = cipher
.encrypt(&n, Payload { msg: pt, aad })
.map_err(|e| wrap_err("ChaCha20Poly1305", e))?;
let mut ret = Vec::with_capacity(n.len() + ct.len());
ret.extend_from_slice(&n);
ret.extend_from_slice(&ct);
Ok(ret)
}
fn decrypt(&self, ct: &[u8], aad: &[u8]) -> Result<Vec<u8>, TinkError> {
if ct.len() < CHA_CHA20_NONCE_SIZE + POLY1305_TAG_SIZE {
return Err("ChaCha20pPly1305: ciphertext too short".into());
}
let cipher = chacha20poly1305::ChaCha20Poly1305::new(&self.key);
let n = chacha20poly1305::Nonce::from_slice(&ct[..CHA_CHA20_NONCE_SIZE]);
cipher
.decrypt(
n,
Payload {
msg: &ct[CHA_CHA20_NONCE_SIZE..],
aad,
},
)
.map_err(|e| wrap_err("ChaCha20Poly1305", e))
}
}
fn new_nonce() -> chacha20poly1305::Nonce {
let iv = tink_core::subtle::random::get_random_bytes(CHA_CHA20_NONCE_SIZE);
*chacha20poly1305::Nonce::from_slice(&iv)
}