Skip to content

Commit e312a03

Browse files
authored
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).
1 parent bdc337c commit e312a03

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

block-cipher/src/lib.rs

+29
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,32 @@ pub trait BlockCipher {
9999
}
100100
}
101101
}
102+
103+
/// Stateful block cipher which permits `&mut self` access.
104+
///
105+
/// The main use case for this trait is hardware encryption engines which
106+
/// require `&mut self` access to an underlying hardware peripheral.
107+
pub trait BlockCipherMut {
108+
/// Size of the block in bytes
109+
type BlockSize: ArrayLength<u8>;
110+
111+
/// Encrypt block in-place
112+
fn encrypt_block(&mut self, block: &mut GenericArray<u8, Self::BlockSize>);
113+
114+
/// Decrypt block in-place
115+
fn decrypt_block(&mut self, block: &mut GenericArray<u8, Self::BlockSize>);
116+
}
117+
118+
impl<Alg: BlockCipher> BlockCipherMut for Alg {
119+
type BlockSize = Alg::BlockSize;
120+
121+
/// Encrypt block in-place
122+
fn encrypt_block(&mut self, block: &mut GenericArray<u8, Self::BlockSize>) {
123+
<Self as BlockCipher>::encrypt_block(self, block);
124+
}
125+
126+
/// Decrypt block in-place
127+
fn decrypt_block(&mut self, block: &mut GenericArray<u8, Self::BlockSize>) {
128+
<Self as BlockCipher>::decrypt_block(self, block);
129+
}
130+
}

0 commit comments

Comments
 (0)