From e312a03b01aa3ee67902c7a2dda2a0d886be7c5b Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Mon, 8 Jun 2020 21:30:51 -0700 Subject: [PATCH] block-cipher: add BlockCipherMut (#179) 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). --- block-cipher/src/lib.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/block-cipher/src/lib.rs b/block-cipher/src/lib.rs index e7ea86e0d..caa9c2973 100644 --- a/block-cipher/src/lib.rs +++ b/block-cipher/src/lib.rs @@ -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; + + /// Encrypt block in-place + fn encrypt_block(&mut self, block: &mut GenericArray); + + /// Decrypt block in-place + fn decrypt_block(&mut self, block: &mut GenericArray); +} + +impl BlockCipherMut for Alg { + type BlockSize = Alg::BlockSize; + + /// Encrypt block in-place + fn encrypt_block(&mut self, block: &mut GenericArray) { + ::encrypt_block(self, block); + } + + /// Decrypt block in-place + fn decrypt_block(&mut self, block: &mut GenericArray) { + ::decrypt_block(self, block); + } +}