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

cipher: add BlockCipher::{encrypt_slice, decrypt_slice} #351

Merged
merged 1 commit into from
Nov 1, 2020
Merged
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
41 changes: 41 additions & 0 deletions cipher/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub use errors::InvalidKeyLength;
// TODO(tarcieri): remove these re-exports in favor of the toplevel one
pub use generic_array::{self, typenum::consts};

use core::convert::TryInto;
use generic_array::{typenum::Unsigned, ArrayLength, GenericArray};

/// Key for an algorithm that implements [`NewBlockCipher`].
Expand Down Expand Up @@ -79,6 +80,26 @@ pub trait BlockCipher {
}
}

/// Encrypt a slice of blocks, leveraging parallelism when available.
#[inline]
fn encrypt_slice(&self, mut blocks: &mut [Block<Self>]) {
let pb = Self::ParBlocks::to_usize();

if pb > 1 {
let mut iter = blocks.chunks_exact_mut(pb);

for chunk in &mut iter {
self.encrypt_blocks(chunk.try_into().unwrap())
}

blocks = iter.into_remainder();
}

for block in blocks {
self.encrypt_block(block);
}
}

/// Decrypt several blocks in parallel using instruction level parallelism
/// if possible.
///
Expand All @@ -89,6 +110,26 @@ pub trait BlockCipher {
self.decrypt_block(block);
}
}

/// Decrypt a slice of blocks, leveraging parallelism when available.
#[inline]
fn decrypt_slice(&self, mut blocks: &mut [Block<Self>]) {
let pb = Self::ParBlocks::to_usize();

if pb > 1 {
let mut iter = blocks.chunks_exact_mut(pb);

for chunk in &mut iter {
self.decrypt_blocks(chunk.try_into().unwrap())
}

blocks = iter.into_remainder();
}

for block in blocks {
self.decrypt_block(block);
}
}
}

/// Stateful block cipher which permits `&mut self` access.
Expand Down