paysec_crypto_rustcrypto/
aes.rs1use aes::cipher::{Array, BlockCipherDecrypt, BlockCipherEncrypt};
2use aes::{Aes128, Aes192, Aes256};
3
4use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, block_padding::NoPadding};
5
6use cmac::{Cmac, Mac};
7
8use paysec_crypto::{AesBlockCipher, AesCbc, AesCmac, AesCmacKeyDerivation};
9
10use crate::{RustCryptoError, RustCryptoProvider, RustCryptoProviderWithRng};
11
12const AES_BLOCK_SIZE: usize = 16;
13
14impl AesBlockCipher<[u8]> for RustCryptoProvider {
15 fn encrypt_block(
16 &self,
17 key: &[u8],
18 block: &[u8; AES_BLOCK_SIZE],
19 ) -> Result<[u8; AES_BLOCK_SIZE], Self::Error> {
20 let mut output = Array::from(*block);
21
22 match key.len() {
23 16 => {
24 let cipher = <Aes128 as aes::cipher::KeyInit>::new_from_slice(key)
25 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
26
27 cipher.encrypt_block(&mut output);
28 }
29
30 24 => {
31 let cipher = <Aes192 as aes::cipher::KeyInit>::new_from_slice(key)
32 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
33
34 cipher.encrypt_block(&mut output);
35 }
36
37 32 => {
38 let cipher = <Aes256 as aes::cipher::KeyInit>::new_from_slice(key)
39 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
40
41 cipher.encrypt_block(&mut output);
42 }
43
44 length => {
45 return Err(RustCryptoError::invalid_key_length(length));
46 }
47 }
48
49 let mut result = [0u8; AES_BLOCK_SIZE];
50 result.copy_from_slice(&output);
51
52 Ok(result)
53 }
54
55 fn decrypt_block(
56 &self,
57 key: &[u8],
58 block: &[u8; AES_BLOCK_SIZE],
59 ) -> Result<[u8; AES_BLOCK_SIZE], Self::Error> {
60 let mut output = Array::from(*block);
61
62 match key.len() {
63 16 => {
64 let cipher = <Aes128 as aes::cipher::KeyInit>::new_from_slice(key)
65 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
66
67 cipher.decrypt_block(&mut output);
68 }
69
70 24 => {
71 let cipher = <Aes192 as aes::cipher::KeyInit>::new_from_slice(key)
72 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
73
74 cipher.decrypt_block(&mut output);
75 }
76
77 32 => {
78 let cipher = <Aes256 as aes::cipher::KeyInit>::new_from_slice(key)
79 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
80
81 cipher.decrypt_block(&mut output);
82 }
83
84 length => {
85 return Err(RustCryptoError::invalid_key_length(length));
86 }
87 }
88
89 let mut result = [0u8; AES_BLOCK_SIZE];
90 result.copy_from_slice(&output);
91
92 Ok(result)
93 }
94}
95
96impl AesCbc<[u8]> for RustCryptoProvider {
97 fn encrypt_cbc(
98 &self,
99 key: &[u8],
100 iv: &[u8; AES_BLOCK_SIZE],
101 plaintext: &[u8],
102 ) -> Result<Vec<u8>, Self::Error> {
103 if plaintext.len() % AES_BLOCK_SIZE != 0 {
104 return Err(RustCryptoError::new(
105 "AES-CBC plaintext length must be a multiple of 16 bytes",
106 ));
107 }
108
109 match key.len() {
110 16 => {
111 let cipher =
112 <cbc::Encryptor<Aes128> as cbc::cipher::KeyIvInit>::new_from_slices(key, iv)
113 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
114
115 Ok(cipher.encrypt_padded_vec::<NoPadding>(plaintext))
116 }
117
118 24 => {
119 let cipher =
120 <cbc::Encryptor<Aes192> as cbc::cipher::KeyIvInit>::new_from_slices(key, iv)
121 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
122
123 Ok(cipher.encrypt_padded_vec::<NoPadding>(plaintext))
124 }
125
126 32 => {
127 let cipher =
128 <cbc::Encryptor<Aes256> as cbc::cipher::KeyIvInit>::new_from_slices(key, iv)
129 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
130
131 Ok(cipher.encrypt_padded_vec::<NoPadding>(plaintext))
132 }
133
134 length => Err(RustCryptoError::invalid_key_length(length)),
135 }
136 }
137
138 fn decrypt_cbc(
139 &self,
140 key: &[u8],
141 iv: &[u8; AES_BLOCK_SIZE],
142 ciphertext: &[u8],
143 ) -> Result<Vec<u8>, Self::Error> {
144 if ciphertext.len() % AES_BLOCK_SIZE != 0 {
145 return Err(RustCryptoError::new(
146 "AES-CBC ciphertext length must be a multiple of 16 bytes",
147 ));
148 }
149
150 match key.len() {
151 16 => {
152 let cipher =
153 <cbc::Decryptor<Aes128> as cbc::cipher::KeyIvInit>::new_from_slices(key, iv)
154 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
155
156 cipher
157 .decrypt_padded_vec::<NoPadding>(ciphertext)
158 .map_err(|_| RustCryptoError::new("AES-CBC decryption failed"))
159 }
160
161 24 => {
162 let cipher =
163 <cbc::Decryptor<Aes192> as cbc::cipher::KeyIvInit>::new_from_slices(key, iv)
164 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
165
166 cipher
167 .decrypt_padded_vec::<NoPadding>(ciphertext)
168 .map_err(|_| RustCryptoError::new("AES-CBC decryption failed"))
169 }
170
171 32 => {
172 let cipher =
173 <cbc::Decryptor<Aes256> as cbc::cipher::KeyIvInit>::new_from_slices(key, iv)
174 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
175
176 cipher
177 .decrypt_padded_vec::<NoPadding>(ciphertext)
178 .map_err(|_| RustCryptoError::new("AES-CBC decryption failed"))
179 }
180
181 length => Err(RustCryptoError::invalid_key_length(length)),
182 }
183 }
184}
185
186impl AesCmac<[u8]> for RustCryptoProvider {
187 fn calculate_cmac(
188 &self,
189 key: &[u8],
190 message: &[u8],
191 ) -> Result<[u8; AES_BLOCK_SIZE], Self::Error> {
192 let bytes = match key.len() {
193 16 => {
194 let mut mac = <Cmac<Aes128> as cmac::KeyInit>::new_from_slice(key)
195 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
196
197 mac.update(message);
198 mac.finalize().into_bytes()
199 }
200
201 24 => {
202 let mut mac = <Cmac<Aes192> as cmac::KeyInit>::new_from_slice(key)
203 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
204
205 mac.update(message);
206 mac.finalize().into_bytes()
207 }
208
209 32 => {
210 let mut mac = <Cmac<Aes256> as cmac::KeyInit>::new_from_slice(key)
211 .map_err(|_| RustCryptoError::invalid_key_length(key.len()))?;
212
213 mac.update(message);
214 mac.finalize().into_bytes()
215 }
216
217 length => {
218 return Err(RustCryptoError::invalid_key_length(length));
219 }
220 };
221
222 let mut result = [0u8; AES_BLOCK_SIZE];
223 result.copy_from_slice(&bytes);
224
225 Ok(result)
226 }
227}
228
229impl AesCmacKeyDerivation<[u8]> for RustCryptoProvider {
230 type DerivedKey = Vec<u8>;
231
232 fn derive_key_cmac(
233 &self,
234 key: &[u8],
235 derivation_inputs: &[&[u8]],
236 output_len: usize,
237 ) -> Result<Self::DerivedKey, Self::Error> {
238 let available_len = derivation_inputs.len() * AES_BLOCK_SIZE;
239
240 if output_len > available_len {
241 return Err(RustCryptoError::new(
242 "insufficient CMAC output for requested derived key length",
243 ));
244 }
245
246 let mut derived_key = Vec::with_capacity(available_len);
247
248 for input in derivation_inputs {
249 let block = <Self as AesCmac<[u8]>>::calculate_cmac(self, key, input)?;
250
251 derived_key.extend_from_slice(&block);
252 }
253
254 derived_key.truncate(output_len);
255
256 Ok(derived_key)
257 }
258}
259
260impl AesCbc<Vec<u8>> for RustCryptoProvider {
267 fn encrypt_cbc(
268 &self,
269 key: &Vec<u8>,
270 iv: &[u8; AES_BLOCK_SIZE],
271 plaintext: &[u8],
272 ) -> Result<Vec<u8>, Self::Error> {
273 <Self as AesCbc<[u8]>>::encrypt_cbc(self, key.as_slice(), iv, plaintext)
274 }
275
276 fn decrypt_cbc(
277 &self,
278 key: &Vec<u8>,
279 iv: &[u8; AES_BLOCK_SIZE],
280 ciphertext: &[u8],
281 ) -> Result<Vec<u8>, Self::Error> {
282 <Self as AesCbc<[u8]>>::decrypt_cbc(self, key.as_slice(), iv, ciphertext)
283 }
284}
285
286impl AesCmac<Vec<u8>> for RustCryptoProvider {
287 fn calculate_cmac(
288 &self,
289 key: &Vec<u8>,
290 message: &[u8],
291 ) -> Result<[u8; AES_BLOCK_SIZE], Self::Error> {
292 <Self as AesCmac<[u8]>>::calculate_cmac(self, key.as_slice(), message)
293 }
294}
295
296impl<R> AesBlockCipher<[u8]> for RustCryptoProviderWithRng<R> {
297 fn encrypt_block(
298 &self,
299 key: &[u8],
300 block: &[u8; AES_BLOCK_SIZE],
301 ) -> Result<[u8; AES_BLOCK_SIZE], Self::Error> {
302 RustCryptoProvider::new().encrypt_block(key, block)
303 }
304
305 fn decrypt_block(
306 &self,
307 key: &[u8],
308 block: &[u8; AES_BLOCK_SIZE],
309 ) -> Result<[u8; AES_BLOCK_SIZE], Self::Error> {
310 RustCryptoProvider::new().decrypt_block(key, block)
311 }
312}
313
314impl<R> AesCbc<[u8]> for RustCryptoProviderWithRng<R> {
315 fn encrypt_cbc(
316 &self,
317 key: &[u8],
318 iv: &[u8; AES_BLOCK_SIZE],
319 plaintext: &[u8],
320 ) -> Result<Vec<u8>, Self::Error> {
321 RustCryptoProvider::new().encrypt_cbc(key, iv, plaintext)
322 }
323
324 fn decrypt_cbc(
325 &self,
326 key: &[u8],
327 iv: &[u8; AES_BLOCK_SIZE],
328 ciphertext: &[u8],
329 ) -> Result<Vec<u8>, Self::Error> {
330 RustCryptoProvider::new().decrypt_cbc(key, iv, ciphertext)
331 }
332}
333
334impl<R> AesCmac<[u8]> for RustCryptoProviderWithRng<R> {
335 fn calculate_cmac(
336 &self,
337 key: &[u8],
338 message: &[u8],
339 ) -> Result<[u8; AES_BLOCK_SIZE], Self::Error> {
340 RustCryptoProvider::new().calculate_cmac(key, message)
341 }
342}
343
344impl<R> AesCmacKeyDerivation<[u8]> for RustCryptoProviderWithRng<R> {
345 type DerivedKey = Vec<u8>;
346
347 fn derive_key_cmac(
348 &self,
349 key: &[u8],
350 derivation_inputs: &[&[u8]],
351 output_len: usize,
352 ) -> Result<Self::DerivedKey, Self::Error> {
353 RustCryptoProvider::new().derive_key_cmac(key, derivation_inputs, output_len)
354 }
355}
356
357impl<R> AesCbc<Vec<u8>> for RustCryptoProviderWithRng<R> {
358 fn encrypt_cbc(
359 &self,
360 key: &Vec<u8>,
361 iv: &[u8; AES_BLOCK_SIZE],
362 plaintext: &[u8],
363 ) -> Result<Vec<u8>, Self::Error> {
364 RustCryptoProvider::new().encrypt_cbc(key, iv, plaintext)
365 }
366
367 fn decrypt_cbc(
368 &self,
369 key: &Vec<u8>,
370 iv: &[u8; AES_BLOCK_SIZE],
371 ciphertext: &[u8],
372 ) -> Result<Vec<u8>, Self::Error> {
373 RustCryptoProvider::new().decrypt_cbc(key, iv, ciphertext)
374 }
375}
376
377impl<R> AesCmac<Vec<u8>> for RustCryptoProviderWithRng<R> {
378 fn calculate_cmac(
379 &self,
380 key: &Vec<u8>,
381 message: &[u8],
382 ) -> Result<[u8; AES_BLOCK_SIZE], Self::Error> {
383 RustCryptoProvider::new().calculate_cmac(key, message)
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 #[test]
392 fn aes_128_block_cipher_matches_known_vector() {
393 let provider = RustCryptoProvider::new();
394
395 let key = hex::decode("000102030405060708090A0B0C0D0E0F").unwrap();
396
397 let plaintext: [u8; 16] = hex::decode("00112233445566778899AABBCCDDEEFF")
398 .unwrap()
399 .try_into()
400 .unwrap();
401
402 let expected: [u8; 16] = hex::decode("69C4E0D86A7B0430D8CDB78070B4C55A")
403 .unwrap()
404 .try_into()
405 .unwrap();
406
407 let encrypted = provider.encrypt_block(key.as_slice(), &plaintext).unwrap();
408
409 assert_eq!(encrypted, expected);
410
411 let decrypted = provider.decrypt_block(key.as_slice(), &encrypted).unwrap();
412
413 assert_eq!(decrypted, plaintext);
414 }
415
416 #[test]
417 fn aes_128_cmac_matches_known_vector() {
418 let provider = RustCryptoProvider::new();
419
420 let key = hex::decode("2B7E151628AED2A6ABF7158809CF4F3C").unwrap();
421
422 let message = hex::decode("6BC1BEE22E409F96E93D7E117393172A").unwrap();
423
424 let expected: [u8; 16] = hex::decode("070A16B46B4D4144F79BDD9DD04A287C")
425 .unwrap()
426 .try_into()
427 .unwrap();
428
429 let result = provider.calculate_cmac(key.as_slice(), &message).unwrap();
430
431 assert_eq!(result, expected);
432 }
433
434 #[test]
435 fn aes_cbc_round_trip_without_padding() {
436 let provider = RustCryptoProvider::new();
437
438 let key = hex::decode("00112233445566778899AABBCCDDEEFF").unwrap();
439
440 let iv = [0u8; 16];
441
442 let plaintext = hex::decode(
443 "00112233445566778899AABBCCDDEEFF\
444 FFEEDDCCBBAA99887766554433221100",
445 )
446 .unwrap();
447
448 let ciphertext = provider
449 .encrypt_cbc(key.as_slice(), &iv, &plaintext)
450 .unwrap();
451
452 let decrypted = provider
453 .decrypt_cbc(key.as_slice(), &iv, &ciphertext)
454 .unwrap();
455
456 assert_eq!(decrypted, plaintext);
457 }
458}