use rand::OsRng;
use ::aead::{ AeadCipher, DecryptFail };
use ::utils::GenNonce;
pub trait SecretBox {
#[inline]
fn seal(key: &[u8], data: &[u8]) -> Vec<u8> {
Self::seal_with_nonce(&mut OsRng::new().unwrap(), key, data)
}
fn seal_with_nonce(rng: &mut GenNonce, key: &[u8], data: &[u8]) -> Vec<u8>;
fn open(key: &[u8], data: &[u8]) -> Result<Vec<u8>, DecryptFail>;
}
impl<T> SecretBox for T where T: AeadCipher {
fn seal_with_nonce(rng: &mut GenNonce, key: &[u8], data: &[u8]) -> Vec<u8> {
let nonce = rng.gen(Self::NONCE_LENGTH);
let output = Self::new(key)
.with_aad(&nonce)
.encrypt(&nonce, data);
[nonce, output].concat()
}
fn open(key: &[u8], data: &[u8]) -> Result<Vec<u8>, DecryptFail> {
if data.len() < Self::TAG_LENGTH + Self::NONCE_LENGTH {
Err(DecryptFail::LengthError)?
};
let (nonce, data) = data.split_at(Self::NONCE_LENGTH);
Self::new(key)
.with_aad(nonce)
.decrypt(nonce, data)
}
}