Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cfb-mode: generic mode block size #32

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion cfb-mode/benches/aes128.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![feature(test)]
extern crate test;

use aes::Aes128;
use aes::{cipher::consts::U1, Aes128};

cipher::block_encryptor_bench!(
KeyIv: cfb_mode::Encryptor<Aes128>,
Expand All @@ -14,3 +14,15 @@ cipher::block_decryptor_bench!(
cfb_aes128_decrypt_block,
cfb_aes128_decrypt_blocks,
);

cipher::block_encryptor_bench!(
KeyIv: cfb_mode::Encryptor<Aes128, U1>,
cfb8_aes128_encrypt_block,
cfb8_aes128_encrypt_blocks,
);

cipher::block_decryptor_bench!(
KeyIv: cfb_mode::Decryptor<Aes128, U1>,
cfb8_aes128_decrypt_block,
cfb8_aes128_decrypt_blocks,
);
135 changes: 135 additions & 0 deletions cfb-mode/src/buf_decrypt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
use cipher::{
crypto_common::{InnerUser, IvSizeUser},
AlgorithmName, Block, BlockCipher, BlockEncryptMut, InnerIvInit, Iv, Unsigned,
};
use core::fmt;

#[cfg(feature = "zeroize")]
use cipher::zeroize::{Zeroize, ZeroizeOnDrop};

/// CFB mode buffered decryptor.
#[derive(Clone)]
pub struct BufDecryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
cipher: C,
iv: Block<C>,
pos: usize,
}

impl<C> BufDecryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
/// Decrypt a buffer in multiple parts.
pub fn decrypt(&mut self, mut data: &mut [u8]) {
let bs = C::BlockSize::to_usize();
let n = data.len();

if n < bs - self.pos {
xor_set2(data, &mut self.iv[self.pos..self.pos + n]);
self.pos += n;
return;
}
let (left, right) = { data }.split_at_mut(bs - self.pos);
data = right;
let mut iv = self.iv.clone();
xor_set2(left, &mut iv[self.pos..]);
self.cipher.encrypt_block_mut(&mut iv);

let mut chunks = data.chunks_exact_mut(bs);
for chunk in &mut chunks {
xor_set2(chunk, iv.as_mut_slice());
self.cipher.encrypt_block_mut(&mut iv);
}

let rem = chunks.into_remainder();
xor_set2(rem, iv.as_mut_slice());
self.pos = rem.len();
self.iv = iv;
}

/// Returns the current state (block and position) of the decryptor.
pub fn get_state(&self) -> (&Block<C>, usize) {
(&self.iv, self.pos)
}

/// Restore from the given state for resumption.
pub fn from_state(cipher: C, iv: &Block<C>, pos: usize) -> Self {
Self {
cipher,
iv: iv.clone(),
pos,
}
}
}

impl<C> InnerUser for BufDecryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
type Inner = C;
}

impl<C> IvSizeUser for BufDecryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
type IvSize = C::BlockSize;
}

impl<C> InnerIvInit for BufDecryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
#[inline]
fn inner_iv_init(mut cipher: C, iv: &Iv<Self>) -> Self {
let mut iv = iv.clone();
cipher.encrypt_block_mut(&mut iv);
Self { cipher, iv, pos: 0 }
}
}

impl<C> AlgorithmName for BufDecryptor<C>
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::BufDecryptor<")?;
<C as AlgorithmName>::write_alg_name(f)?;
f.write_str(">")
}
}

impl<C> fmt::Debug for BufDecryptor<C>
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::BufDecryptor<")?;
<C as AlgorithmName>::write_alg_name(f)?;
f.write_str("> { ... }")
}
}

#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl<C: BlockEncryptMut + BlockCipher> Drop for BufDecryptor<C> {
fn drop(&mut self) {
self.iv.zeroize();
}
}

#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl<C: BlockEncryptMut + BlockCipher + ZeroizeOnDrop> ZeroizeOnDrop for BufDecryptor<C> {}

#[inline(always)]
fn xor_set2(buf1: &mut [u8], buf2: &mut [u8]) {
for (a, b) in buf1.iter_mut().zip(buf2) {
let t = *a;
*a ^= *b;
*b = t;
}
}
136 changes: 136 additions & 0 deletions cfb-mode/src/buf_encrypt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
use cipher::{
crypto_common::{InnerUser, IvSizeUser},
AlgorithmName, Block, BlockCipher, BlockEncryptMut, InnerIvInit, Iv, Unsigned,
};
use core::fmt;

#[cfg(feature = "zeroize")]
use cipher::zeroize::{Zeroize, ZeroizeOnDrop};

/// CFB mode buffered encryptor.
#[derive(Clone)]
pub struct BufEncryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
cipher: C,
iv: Block<C>,
pos: usize,
}

impl<C> BufEncryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
/// Encrypt a buffer in multiple parts.
pub fn encrypt(&mut self, mut data: &mut [u8]) {
let bs = C::BlockSize::USIZE;
let n = data.len();

if n < bs - self.pos {
xor_set1(data, &mut self.iv[self.pos..self.pos + n]);
self.pos += n;
return;
}

let (left, right) = { data }.split_at_mut(bs - self.pos);
data = right;
let mut iv = self.iv.clone();
xor_set1(left, &mut iv[self.pos..]);
self.cipher.encrypt_block_mut(&mut iv);

let mut chunks = data.chunks_exact_mut(bs);
for chunk in &mut chunks {
xor_set1(chunk, iv.as_mut_slice());
self.cipher.encrypt_block_mut(&mut iv);
}

let rem = chunks.into_remainder();
xor_set1(rem, iv.as_mut_slice());
self.pos = rem.len();
self.iv = iv;
}

/// Returns the current state (block and position) of the decryptor.
pub fn get_state(&self) -> (&Block<C>, usize) {
(&self.iv, self.pos)
}

/// Restore from the given state for resumption.
pub fn from_state(cipher: C, iv: &Block<C>, pos: usize) -> Self {
Self {
cipher,
iv: iv.clone(),
pos,
}
}
}

impl<C> InnerUser for BufEncryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
type Inner = C;
}

impl<C> IvSizeUser for BufEncryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
type IvSize = C::BlockSize;
}

impl<C> InnerIvInit for BufEncryptor<C>
where
C: BlockEncryptMut + BlockCipher,
{
#[inline]
fn inner_iv_init(mut cipher: C, iv: &Iv<Self>) -> Self {
let mut iv = iv.clone();
cipher.encrypt_block_mut(&mut iv);
Self { cipher, iv, pos: 0 }
}
}

impl<C> AlgorithmName for BufEncryptor<C>
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::BufEncryptor<")?;
<C as AlgorithmName>::write_alg_name(f)?;
f.write_str(">")
}
}

impl<C> fmt::Debug for BufEncryptor<C>
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::BufEncryptor<")?;
<C as AlgorithmName>::write_alg_name(f)?;
f.write_str("> { ... }")
}
}

#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl<C: BlockEncryptMut + BlockCipher> Drop for BufEncryptor<C> {
fn drop(&mut self) {
self.iv.zeroize();
}
}

#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl<C: BlockEncryptMut + BlockCipher + ZeroizeOnDrop> ZeroizeOnDrop for BufEncryptor<C> {}

#[inline(always)]
fn xor_set1(buf1: &mut [u8], buf2: &mut [u8]) {
for (a, b) in buf1.iter_mut().zip(buf2) {
let t = *a ^ *b;
*a = t;
*b = t;
}
}
Loading