Skip to content

Commit

Permalink
block-cipher: add BlockCipherMut
Browse files Browse the repository at this point in the history
Adds a stateful equivalent to `BlockCipher` that permits `&mut self`
access to the underlying type.

The main use case for this trait is hardware cryptographic accelerators
which need to e.g. communitate with a peripheral device via an
underlying `&mut` reference.

While it's possible to use some underlying logic to use the existing
`BlockCipher` trait in such a scenario, the solutions are somewhat ugly.
Here is a real-world example:

https://github.com/iqlusioninc/usbarmory.rs/blob/develop/firmware/usbarmory/src/dcp/aes128.rs#L198-L236

The idea with `BlockCipherMut` would be to alternatively provide
`AeadMut`/`AeadMutInPlace` for AEAD modes with an underlying
`BlockCipherMut` (when possible).
  • Loading branch information
tarcieri committed Jun 9, 2020
1 parent bdc337c commit 680bb66
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions block-cipher/src/lib.rs
Expand Up @@ -99,3 +99,32 @@ pub trait BlockCipher {
}
}
}

/// Stateful block cipher which permits `&mut self` access.
///
/// The main use case for this trait is hardware encryption engines which
/// require `&mut self` access to an underlying hardware peripheral.
pub trait BlockCipherMut {
/// Size of the block in bytes
type BlockSize: ArrayLength<u8>;

/// Encrypt block in-place
fn encrypt_block(&mut self, block: &mut GenericArray<u8, Self::BlockSize>);

/// Decrypt block in-place
fn decrypt_block(&mut self, block: &mut GenericArray<u8, Self::BlockSize>);
}

impl<Alg: BlockCipher> BlockCipherMut for Alg {
type BlockSize = Alg::BlockSize;

/// Encrypt block in-place
fn encrypt_block(&mut self, block: &mut GenericArray<u8, Self::BlockSize>) {
<Self as BlockCipher>::encrypt_block(self, block);
}

/// Decrypt block in-place
fn decrypt_block(&mut self, block: &mut GenericArray<u8, Self::BlockSize>) {
<Self as BlockCipher>::decrypt_block(self, block);
}
}

0 comments on commit 680bb66

Please sign in to comment.