#![no_std]
#![doc(html_logo_url =
"https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")]
pub extern crate generic_array;
#[cfg(feature = "dev")]
pub extern crate blobby;
#[cfg(feature = "std")]
extern crate std;
use generic_array::{GenericArray, ArrayLength};
use generic_array::typenum::Unsigned;
#[cfg(feature = "dev")]
pub mod dev;
mod errors;
pub use errors::{LoopError, InvalidKeyNonceLength};
pub trait NewStreamCipher: Sized {
type KeySize: ArrayLength<u8>;
type NonceSize: ArrayLength<u8>;
fn new(
key: &GenericArray<u8, Self::KeySize>,
nonce: &GenericArray<u8, Self::NonceSize>,
) -> Self;
#[inline]
fn new_var(key: &[u8], nonce: &[u8]) -> Result<Self, InvalidKeyNonceLength> {
let kl = Self::KeySize::to_usize();
let nl = Self::NonceSize::to_usize();
if key.len() != kl || nonce.len() != nl {
Err(InvalidKeyNonceLength)
} else {
let key = GenericArray::from_slice(key);
let nonce = GenericArray::from_slice(nonce);
Ok(Self::new(key, nonce))
}
}
}
pub trait SyncStreamCipher {
#[inline]
fn apply_keystream(&mut self, data: &mut [u8]) {
let res = self.try_apply_keystream(data);
if res.is_err() {
panic!("stream cipher loop detected");
}
}
fn try_apply_keystream(&mut self, data: &mut [u8]) -> Result<(), LoopError>;
}
pub trait SyncStreamCipherSeek {
fn current_pos(&self) -> u64;
fn seek(&mut self, pos: u64);
}
pub trait StreamCipher {
fn encrypt(&mut self, data: &mut [u8]);
fn decrypt(&mut self, data: &mut [u8]);
}
impl<C: SyncStreamCipher> StreamCipher for C {
#[inline(always)]
fn encrypt(&mut self, data: &mut [u8]) {
SyncStreamCipher::apply_keystream(self, data);
}
#[inline(always)]
fn decrypt(&mut self, data: &mut [u8]) {
SyncStreamCipher::apply_keystream(self, data);
}
}