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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#[cfg(feature = "alloc")]
use crate::prelude::*;
use crate::{error::Error, Aes128, Aes256, IV_SIZE};
use cmac::Cmac;
use crypto_mac::Mac;
use ctr::Ctr128;
use dbl::Dbl;
use generic_array::{
typenum::{Unsigned, U16},
GenericArray,
};
use pmac::Pmac;
use stream_cipher::{NewStreamCipher, SyncStreamCipher};
use subtle::ConstantTimeEq;
use zeroize::Zeroize;
pub const MAX_HEADERS: usize = 126;
type SivArray = GenericArray<u8, U16>;
pub struct Siv<C, M>
where
C: NewStreamCipher<NonceSize = U16> + SyncStreamCipher,
M: Mac<OutputSize = U16>,
{
encryption_key: GenericArray<u8, <C as NewStreamCipher>::KeySize>,
mac: M,
}
pub type CmacSiv<BlockCipher> = Siv<Ctr128<BlockCipher>, Cmac<BlockCipher>>;
pub type PmacSiv<BlockCipher> = Siv<Ctr128<BlockCipher>, Pmac<BlockCipher>>;
pub type Aes128Siv = CmacSiv<Aes128>;
pub type Aes256Siv = CmacSiv<Aes256>;
pub type Aes128PmacSiv = PmacSiv<Aes128>;
pub type Aes256PmacSiv = PmacSiv<Aes256>;
impl<C, M> Siv<C, M>
where
C: NewStreamCipher<NonceSize = U16> + SyncStreamCipher,
M: Mac<OutputSize = U16>,
{
pub fn new(key: &[u8]) -> Self {
let key_size = M::KeySize::to_usize() * 2;
assert_eq!(
key.len(),
key_size,
"expected {}-byte key, got {}",
key_size,
key.len()
);
let encryption_key = GenericArray::clone_from_slice(&key[(key_size / 2)..]);
let mac = M::new(GenericArray::from_slice(&key[..(key_size / 2)]));
Self {
encryption_key,
mac,
}
}
pub fn seal_in_place<I, T>(&mut self, headers: I, plaintext: &mut [u8])
where
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
if plaintext.len() < IV_SIZE {
panic!("plaintext buffer too small to hold MAC tag!");
}
let (siv_tag, msg) = plaintext.split_at_mut(IV_SIZE);
siv_tag.copy_from_slice(&s2v(&mut self.mac, headers, msg));
self.xor_with_keystream(siv_tag, msg);
}
pub fn open_in_place<'a, I, T>(
&mut self,
headers: I,
ciphertext: &'a mut [u8],
) -> Result<&'a [u8], Error>
where
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
if ciphertext.len() < IV_SIZE {
return Err(Error);
}
let (siv_tag, msg) = ciphertext.split_at_mut(IV_SIZE);
self.xor_with_keystream(siv_tag, msg);
let computed_siv_tag = s2v(&mut self.mac, headers, msg);
let siv_tag_is_authentic = computed_siv_tag.as_slice().ct_eq(siv_tag).into();
if siv_tag_is_authentic {
Ok(msg)
} else {
self.xor_with_keystream(siv_tag, msg);
Err(Error)
}
}
#[cfg(feature = "alloc")]
pub fn seal<I, T>(&mut self, associated_data: I, plaintext: &[u8]) -> Vec<u8>
where
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
let mut buffer = vec![0; IV_SIZE + plaintext.len()];
buffer[IV_SIZE..].copy_from_slice(plaintext);
self.seal_in_place(associated_data, &mut buffer);
buffer
}
#[cfg(feature = "alloc")]
pub fn open<I, T>(&mut self, associated_data: I, ciphertext: &[u8]) -> Result<Vec<u8>, Error>
where
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
let mut buffer = Vec::from(ciphertext);
self.open_in_place(associated_data, &mut buffer)?;
buffer.drain(..IV_SIZE);
Ok(buffer)
}
fn xor_with_keystream(&mut self, iv: &[u8], msg: &mut [u8]) {
let mut zeroed_iv = SivArray::clone_from_slice(iv);
zeroed_iv[8] &= 0x7f;
zeroed_iv[12] &= 0x7f;
C::new(GenericArray::from_slice(&self.encryption_key), &zeroed_iv).apply_keystream(msg);
}
}
impl<C, M> Drop for Siv<C, M>
where
C: NewStreamCipher<NonceSize = U16> + SyncStreamCipher,
M: Mac<OutputSize = U16>,
{
fn drop(&mut self) {
self.encryption_key.zeroize()
}
}
pub fn s2v<M, I, T>(mac: &mut M, headers: I, message: &[u8]) -> GenericArray<u8, U16>
where
M: Mac<OutputSize = U16>,
I: IntoIterator<Item = T>,
T: AsRef<[u8]>,
{
mac.input(&SivArray::default());
let mut state = mac.result_reset().code();
for (i, header) in headers.into_iter().enumerate() {
if i >= MAX_HEADERS {
panic!("too many associated data items!");
}
state = state.dbl();
mac.input(header.as_ref());
let code = mac.result_reset().code();
xor_in_place(&mut state, &code);
}
if message.len() >= IV_SIZE {
let n = message.len().checked_sub(IV_SIZE).unwrap();
mac.input(&message[..n]);
xor_in_place(&mut state, &message[n..]);
} else {
state = state.dbl();
xor_in_place(&mut state, message);
state[message.len()] ^= 0x80;
};
mac.input(state.as_ref());
mac.result_reset().code()
}
#[inline]
fn xor_in_place(dst: &mut [u8], src: &[u8]) {
for (a, b) in dst[..src.len()].iter_mut().zip(src) {
*a ^= *b;
}
}