Skip to content

Commit

Permalink
cipher: add BlockCipher::{encrypt_slice, decrypt_slice} (#351)
Browse files Browse the repository at this point in the history
Partially addresses #332.

Adds methods which work over an arbitrarily sized slice of blocks to
encrypt/decrypt.

Provides a default implementation, but can be potentially further
optimized by individual implementations.
  • Loading branch information
tarcieri committed Nov 1, 2020
1 parent 79254b0 commit a2c62c5
Showing 1 changed file with 41 additions and 0 deletions.
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

0 comments on commit a2c62c5

Please sign in to comment.