1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use block_cipher::generic_array::{
typenum::{Unsigned, U16},
ArrayLength, GenericArray,
};
use block_cipher::BlockCipher;
use core::{convert::TryInto, marker::PhantomData, mem};
type Block128 = GenericArray<u8, U16>;
pub(crate) const BLOCK_SIZE: usize = 16;
pub(crate) struct Ctr32<Aes>
where
Aes: BlockCipher<BlockSize = U16>,
Aes::ParBlocks: ArrayLength<GenericArray<u8, Aes::BlockSize>>,
{
block_cipher: PhantomData<Aes>,
buffer: GenericArray<Block128, Aes::ParBlocks>,
counter_block: Block128,
base_counter: u32,
}
impl<Aes> Ctr32<Aes>
where
Aes: BlockCipher<BlockSize = U16>,
Aes::ParBlocks: ArrayLength<GenericArray<u8, Aes::BlockSize>>,
{
pub fn new(j0: Block128) -> Self {
let base_counter = u32::from_be_bytes(j0[12..].try_into().unwrap());
#[allow(unsafe_code)]
Self {
block_cipher: PhantomData,
buffer: unsafe { mem::zeroed() },
counter_block: j0,
base_counter,
}
}
pub fn seek(&mut self, new_counter_value: u32) {
self.counter_block[12..].copy_from_slice(
&new_counter_value
.wrapping_add(self.base_counter)
.to_be_bytes(),
);
}
pub fn apply_keystream(&mut self, block_cipher: &Aes, msg: &mut [u8]) {
for chunk in msg.chunks_mut(BLOCK_SIZE * Aes::ParBlocks::to_usize()) {
self.apply_keystream_blocks(block_cipher, chunk);
}
}
fn apply_keystream_blocks(&mut self, block_cipher: &Aes, msg: &mut [u8]) {
let mut counter = u32::from_be_bytes(self.counter_block[12..].try_into().unwrap());
let n_blocks = msg.chunks(BLOCK_SIZE).count();
debug_assert!(n_blocks <= Aes::ParBlocks::to_usize());
for block in self.buffer.iter_mut().take(n_blocks) {
*block = self.counter_block;
counter = counter.wrapping_add(1);
self.counter_block[12..].copy_from_slice(&counter.to_be_bytes());
}
if n_blocks == 1 {
block_cipher.encrypt_block(&mut self.buffer[0]);
} else {
block_cipher.encrypt_blocks(&mut self.buffer);
}
for (i, chunk) in msg.chunks_mut(BLOCK_SIZE).enumerate() {
let keystream_block = &self.buffer[i];
for (i, byte) in chunk.iter_mut().enumerate() {
*byte ^= keystream_block[i];
}
}
}
}