1use crate::aws_lc::{
5 EVP_CIPHER_CTX_new, EVP_CIPHER_iv_length, EVP_CIPHER_key_length, EVP_DecryptFinal_ex,
6 EVP_DecryptInit_ex, EVP_DecryptUpdate, EVP_EncryptFinal_ex, EVP_EncryptInit_ex,
7 EVP_EncryptUpdate, EVP_CIPHER, EVP_CIPHER_CTX,
8};
9use crate::cipher::{
10 Algorithm, DecryptionContext, EncryptionContext, OperatingMode, UnboundCipherKey,
11};
12use crate::error::Unspecified;
13use crate::fips::indicator_check;
14use crate::ptr::LcPtr;
15use std::ptr::{null, null_mut};
16
17use super::ConstPointer;
18
19pub struct StreamingEncryptingKey {
21 algorithm: &'static Algorithm,
22 mode: OperatingMode,
23 cipher_ctx: LcPtr<EVP_CIPHER_CTX>,
24 context: EncryptionContext,
25 output_generated: usize,
26}
27
28unsafe impl Send for StreamingEncryptingKey {}
29
30pub struct BufferUpdate<'a> {
33 written: &'a [u8],
34 remainder: &'a mut [u8],
35}
36
37impl<'a> BufferUpdate<'a> {
38 fn new(out_buffer: &'a mut [u8], written_len: usize) -> Self {
39 let (written, remainder) = out_buffer.split_at_mut(written_len);
40 Self { written, remainder }
41 }
42}
43
44impl BufferUpdate<'_> {
45 #[must_use]
47 pub fn written(&self) -> &[u8] {
48 self.written
49 }
50
51 #[must_use]
53 pub fn remainder(&self) -> &[u8] {
54 self.remainder
55 }
56
57 #[must_use]
59 pub fn remainder_mut(&mut self) -> &mut [u8] {
60 self.remainder
61 }
62}
63
64fn evp_encrypt_init(
65 cipher_ctx: &mut LcPtr<EVP_CIPHER_CTX>,
66 cipher: &ConstPointer<EVP_CIPHER>,
67 key: &[u8],
68 iv: Option<&[u8]>,
69) -> Result<(), Unspecified> {
70 let iv_ptr: *const u8 = if let Some(iv) = iv {
71 iv.as_ptr()
72 } else {
73 null()
74 };
75
76 if 1 != unsafe {
78 EVP_EncryptInit_ex(
79 cipher_ctx.as_mut_ptr(),
80 cipher.as_const_ptr(),
81 null_mut(),
82 key.as_ptr(),
83 iv_ptr,
84 )
85 } {
86 return Err(Unspecified);
87 }
88
89 Ok(())
90}
91
92fn evp_decrypt_init(
93 cipher_ctx: &mut LcPtr<EVP_CIPHER_CTX>,
94 cipher: &ConstPointer<EVP_CIPHER>,
95 key: &[u8],
96 iv: Option<&[u8]>,
97) -> Result<(), Unspecified> {
98 let iv_ptr: *const u8 = if let Some(iv) = iv {
99 iv.as_ptr()
100 } else {
101 null()
102 };
103
104 if 1 != unsafe {
106 EVP_DecryptInit_ex(
107 cipher_ctx.as_mut_ptr(),
108 cipher.as_const_ptr(),
109 null_mut(),
110 key.as_ptr(),
111 iv_ptr,
112 )
113 } {
114 return Err(Unspecified);
115 }
116
117 Ok(())
118}
119
120impl StreamingEncryptingKey {
121 #[allow(clippy::needless_pass_by_value)]
122 fn new(
123 key: UnboundCipherKey,
124 mode: OperatingMode,
125 context: EncryptionContext,
126 ) -> Result<Self, Unspecified> {
127 let algorithm = key.algorithm();
128 if !algorithm.supports_mode(mode) {
129 return Err(Unspecified);
130 }
131 key.validate_key_material()?;
136 let mut cipher_ctx = LcPtr::new(unsafe { EVP_CIPHER_CTX_new() })?;
137 let cipher = mode.evp_cipher(key.algorithm);
138 let key_bytes = key.key_bytes.as_ref();
139 if key_bytes.len()
140 != <usize>::try_from(unsafe { EVP_CIPHER_key_length(cipher.as_const_ptr()) }).unwrap()
141 {
142 return Err(Unspecified);
143 }
144
145 match &context {
146 ctx @ EncryptionContext::Iv128(..) => {
147 let iv = <&[u8]>::try_from(ctx)?;
148 debug_assert_eq!(
149 iv.len(),
150 <usize>::try_from(unsafe { EVP_CIPHER_iv_length(cipher.as_const_ptr()) })
151 .unwrap()
152 );
153 evp_encrypt_init(&mut cipher_ctx, &cipher, key_bytes, Some(iv))?;
154 }
155 #[cfg(feature = "legacy-des")]
156 ctx @ EncryptionContext::Iv64(..) => {
157 let iv = <&[u8]>::try_from(ctx)?;
158 debug_assert_eq!(
159 iv.len(),
160 <usize>::try_from(unsafe { EVP_CIPHER_iv_length(cipher.as_const_ptr()) })
161 .unwrap()
162 );
163 evp_encrypt_init(&mut cipher_ctx, &cipher, key_bytes, Some(iv))?;
164 }
165 EncryptionContext::None => {
166 evp_encrypt_init(&mut cipher_ctx, &cipher, key_bytes, None)?;
167 }
168 }
169
170 Ok(Self {
171 algorithm,
172 mode,
173 cipher_ctx,
174 context,
175 output_generated: 0,
176 })
177 }
178
179 fn update_internal<'a>(
180 &mut self,
181 input: &[u8],
182 output: &'a mut [u8],
183 min_outsize: usize,
184 ) -> Result<BufferUpdate<'a>, Unspecified> {
185 if output.len() < min_outsize {
186 return Err(Unspecified);
187 }
188 let mut outlen: i32 = 0;
189 let inlen: i32 = input.len().try_into()?;
190
191 if 1 != unsafe {
192 EVP_EncryptUpdate(
193 self.cipher_ctx.as_mut_ptr(),
194 output.as_mut_ptr(),
195 &mut outlen,
196 input.as_ptr(),
197 inlen,
198 )
199 } {
200 return Err(Unspecified);
201 }
202 let outlen: usize = outlen.try_into()?;
203 debug_assert!(outlen <= min_outsize);
204 self.output_generated += outlen;
205 assert!(outlen <= output.len());
206
207 Ok(BufferUpdate::new(output, outlen))
208 }
209
210 pub fn update<'a>(
221 &mut self,
222 input: &[u8],
223 output: &'a mut [u8],
224 ) -> Result<BufferUpdate<'a>, Unspecified> {
225 let min_outsize = input
226 .len()
227 .checked_add(self.algorithm().block_len())
228 .ok_or(Unspecified)?
229 .checked_sub(1)
230 .ok_or(Unspecified)?;
231 self.update_internal(input, output, min_outsize)
232 }
233
234 pub fn less_safe_update<'a>(
256 &mut self,
257 input: &[u8],
258 output: &'a mut [u8],
259 ) -> Result<BufferUpdate<'a>, Unspecified> {
260 let next_total = self
261 .output_generated
262 .checked_add(input.len())
263 .ok_or(Unspecified)?;
264 let extra_buffer_size = (self.algorithm().block_len
265 - next_total.rem_euclid(self.algorithm().block_len))
266 .rem_euclid(self.algorithm().block_len);
267 let min_outsize = input
268 .len()
269 .checked_add(extra_buffer_size)
270 .ok_or(Unspecified)?;
271 self.update_internal(input, output, min_outsize)
272 }
273
274 pub fn finish(
284 mut self,
285 output: &mut [u8],
286 ) -> Result<(DecryptionContext, BufferUpdate<'_>), Unspecified> {
287 if output.len() < self.algorithm().block_len() {
288 return Err(Unspecified);
289 }
290 let mut outlen: i32 = 0;
291
292 if 1 != indicator_check!(unsafe {
293 EVP_EncryptFinal_ex(
294 self.cipher_ctx.as_mut_ptr(),
295 output.as_mut_ptr(),
296 &mut outlen,
297 )
298 }) {
299 return Err(Unspecified);
300 }
301 let outlen: usize = outlen.try_into()?;
302 debug_assert!(outlen <= self.algorithm().block_len());
303 Ok((self.context.into(), BufferUpdate::new(output, outlen)))
304 }
305
306 #[must_use]
308 pub fn mode(&self) -> OperatingMode {
309 self.mode
310 }
311
312 #[must_use]
314 pub fn algorithm(&self) -> &'static Algorithm {
315 self.algorithm
316 }
317
318 pub fn ctr(key: UnboundCipherKey) -> Result<Self, Unspecified> {
327 let context = key.algorithm().new_encryption_context(OperatingMode::CTR)?;
328 Self::less_safe_ctr(key, context)
329 }
330
331 pub fn less_safe_ctr(
343 key: UnboundCipherKey,
344 context: EncryptionContext,
345 ) -> Result<Self, Unspecified> {
346 Self::new(key, OperatingMode::CTR, context)
347 }
348
349 pub fn cbc_pkcs7(key: UnboundCipherKey) -> Result<Self, Unspecified> {
362 let context = key.algorithm().new_encryption_context(OperatingMode::CBC)?;
363 Self::less_safe_cbc_pkcs7(key, context)
364 }
365
366 pub fn cfb128(key: UnboundCipherKey) -> Result<Self, Unspecified> {
375 let context = key
376 .algorithm()
377 .new_encryption_context(OperatingMode::CFB128)?;
378 Self::less_safe_cfb128(key, context)
379 }
380
381 pub fn ecb_pkcs7(key: UnboundCipherKey) -> Result<Self, Unspecified> {
396 let context = key.algorithm().new_encryption_context(OperatingMode::ECB)?;
397 Self::new(key, OperatingMode::ECB, context)
398 }
399
400 pub fn less_safe_cfb128(
412 key: UnboundCipherKey,
413 context: EncryptionContext,
414 ) -> Result<Self, Unspecified> {
415 Self::new(key, OperatingMode::CFB128, context)
416 }
417
418 pub fn less_safe_cbc_pkcs7(
434 key: UnboundCipherKey,
435 context: EncryptionContext,
436 ) -> Result<Self, Unspecified> {
437 Self::new(key, OperatingMode::CBC, context)
438 }
439}
440
441pub struct StreamingDecryptingKey {
443 algorithm: &'static Algorithm,
444 mode: OperatingMode,
445 cipher_ctx: LcPtr<EVP_CIPHER_CTX>,
446 output_generated: usize,
447}
448
449unsafe impl Send for StreamingDecryptingKey {}
450
451impl StreamingDecryptingKey {
452 #[allow(clippy::needless_pass_by_value)]
453 fn new(
454 key: UnboundCipherKey,
455 mode: OperatingMode,
456 context: DecryptionContext,
457 ) -> Result<Self, Unspecified> {
458 let algorithm = key.algorithm();
459 if !algorithm.supports_mode(mode) {
460 return Err(Unspecified);
461 }
462 key.validate_key_material()?;
464 let mut cipher_ctx = LcPtr::new(unsafe { EVP_CIPHER_CTX_new() })?;
465 let cipher = mode.evp_cipher(key.algorithm);
466 let key_bytes = key.key_bytes.as_ref();
467 if key_bytes.len()
468 != <usize>::try_from(unsafe { EVP_CIPHER_key_length(cipher.as_const_ptr()) }).unwrap()
469 {
470 return Err(Unspecified);
471 }
472
473 match &context {
474 ctx @ DecryptionContext::Iv128(..) => {
475 let iv = <&[u8]>::try_from(ctx)?;
476 debug_assert_eq!(
477 iv.len(),
478 <usize>::try_from(unsafe { EVP_CIPHER_iv_length(cipher.as_const_ptr()) })
479 .unwrap()
480 );
481 evp_decrypt_init(&mut cipher_ctx, &cipher, key_bytes, Some(iv))?;
482 }
483 #[cfg(feature = "legacy-des")]
484 ctx @ DecryptionContext::Iv64(..) => {
485 let iv = <&[u8]>::try_from(ctx)?;
486 debug_assert_eq!(
487 iv.len(),
488 <usize>::try_from(unsafe { EVP_CIPHER_iv_length(cipher.as_const_ptr()) })
489 .unwrap()
490 );
491 evp_decrypt_init(&mut cipher_ctx, &cipher, key_bytes, Some(iv))?;
492 }
493 DecryptionContext::None => {
494 evp_decrypt_init(&mut cipher_ctx, &cipher, key_bytes, None)?;
495 }
496 }
497
498 Ok(Self {
499 algorithm,
500 mode,
501 cipher_ctx,
502 output_generated: 0,
503 })
504 }
505
506 fn update_internal<'a>(
507 &mut self,
508 input: &[u8],
509 output: &'a mut [u8],
510 min_outsize: usize,
511 ) -> Result<BufferUpdate<'a>, Unspecified> {
512 if output.len() < min_outsize {
513 return Err(Unspecified);
514 }
515 let mut outlen: i32 = 0;
516 let inlen: i32 = input.len().try_into()?;
517
518 if 1 != unsafe {
519 EVP_DecryptUpdate(
520 self.cipher_ctx.as_mut_ptr(),
521 output.as_mut_ptr(),
522 &mut outlen,
523 input.as_ptr(),
524 inlen,
525 )
526 } {
527 return Err(Unspecified);
528 }
529 let outlen: usize = outlen.try_into()?;
530 debug_assert!(outlen <= min_outsize);
531 self.output_generated += outlen;
532 assert!(outlen <= output.len());
535
536 Ok(BufferUpdate::new(output, outlen))
537 }
538
539 pub fn update<'a>(
550 &mut self,
551 input: &[u8],
552 output: &'a mut [u8],
553 ) -> Result<BufferUpdate<'a>, Unspecified> {
554 let min_outsize = input
555 .len()
556 .checked_add(self.algorithm().block_len())
557 .ok_or(Unspecified)?
558 .checked_sub(1)
559 .ok_or(Unspecified)?;
560 self.update_internal(input, output, min_outsize)
561 }
562
563 pub fn less_safe_update<'a>(
585 &mut self,
586 input: &[u8],
587 output: &'a mut [u8],
588 ) -> Result<BufferUpdate<'a>, Unspecified> {
589 let next_total = self
590 .output_generated
591 .checked_add(input.len())
592 .ok_or(Unspecified)?;
593 let extra_buffer_size = (self.algorithm().block_len
594 - next_total.rem_euclid(self.algorithm().block_len))
595 .rem_euclid(self.algorithm().block_len);
596 let min_outsize = input
597 .len()
598 .checked_add(extra_buffer_size)
599 .ok_or(Unspecified)?;
600 self.update_internal(input, output, min_outsize)
601 }
602
603 pub fn finish(mut self, output: &mut [u8]) -> Result<BufferUpdate<'_>, Unspecified> {
612 if output.len() < self.algorithm().block_len() {
613 return Err(Unspecified);
614 }
615 let mut outlen: i32 = 0;
616
617 if 1 != indicator_check!(unsafe {
618 EVP_DecryptFinal_ex(
619 self.cipher_ctx.as_mut_ptr(),
620 output.as_mut_ptr(),
621 &mut outlen,
622 )
623 }) {
624 return Err(Unspecified);
625 }
626 let outlen: usize = outlen.try_into()?;
627 debug_assert!(outlen <= self.algorithm().block_len());
628 Ok(BufferUpdate::new(output, outlen))
629 }
630
631 #[must_use]
633 pub fn mode(&self) -> OperatingMode {
634 self.mode
635 }
636
637 #[must_use]
639 pub fn algorithm(&self) -> &'static Algorithm {
640 self.algorithm
641 }
642
643 pub fn ctr(key: UnboundCipherKey, context: DecryptionContext) -> Result<Self, Unspecified> {
652 Self::new(key, OperatingMode::CTR, context)
653 }
654
655 pub fn cbc_pkcs7(
666 key: UnboundCipherKey,
667 context: DecryptionContext,
668 ) -> Result<Self, Unspecified> {
669 Self::new(key, OperatingMode::CBC, context)
670 }
671
672 pub fn cfb128(key: UnboundCipherKey, context: DecryptionContext) -> Result<Self, Unspecified> {
681 Self::new(key, OperatingMode::CFB128, context)
682 }
683
684 pub fn ecb_pkcs7(
699 key: UnboundCipherKey,
700 context: DecryptionContext,
701 ) -> Result<Self, Unspecified> {
702 Self::new(key, OperatingMode::ECB, context)
703 }
704}
705
706#[cfg(test)]
707mod tests {
708 use crate::cipher::{
709 DecryptionContext, EncryptionContext, OperatingMode, StreamingDecryptingKey,
710 StreamingEncryptingKey, UnboundCipherKey, AES_128, AES_128_KEY_LEN, AES_256,
711 AES_256_KEY_LEN,
712 };
713 use crate::iv::{FixedLength, IV_LEN_128_BIT};
714 use crate::rand::{SecureRandom, SystemRandom};
715 use crate::test::from_hex;
716 use paste::*;
717
718 const OUTPUT_CANARIES: [u8; 2] = [0xAA, 0x55];
723
724 fn assert_no_write_past(output: &[u8], slice_start: usize, slice_end: usize, canary: u8) {
725 let slice_len = slice_end - slice_start;
726 let tail = &output[slice_end..output.len().min(slice_end + 16)];
727 assert!(
728 output[slice_end..].iter().all(|&b| b == canary),
729 "wrote past the provided {slice_len}-byte output slice at buffer offsets \
730 {slice_start}..{slice_end} \
731 (canary {canary:#04x}, bytes at {slice_end}..: {tail:02x?})"
732 );
733 }
734
735 fn apply_update_with_canary(
736 output: &mut [u8],
737 out_idx: usize,
738 out_end: usize,
739 canary: u8,
740 op: impl FnOnce(&mut [u8]) -> usize,
741 ) -> usize {
742 output[out_end..].fill(canary);
743 let written = op(&mut output[out_idx..out_end]);
744 assert_no_write_past(output, out_idx, out_end, canary);
745 written
746 }
747
748 fn step_encrypt_with_updater<F>(
752 mut encrypting_key: StreamingEncryptingKey,
753 plaintext: &[u8],
754 step: usize,
755 canary: u8,
756 mut updater: F,
757 ) -> (Box<[u8]>, DecryptionContext)
758 where
759 F: FnMut(&mut StreamingEncryptingKey, &[u8], &mut [u8], usize, usize, usize) -> usize,
760 {
761 let alg = encrypting_key.algorithm();
762 let mode = encrypting_key.mode();
763 let block_len = alg.block_len();
764 let n = plaintext.len();
765 let mut ciphertext = vec![canary; n + 2 * block_len];
768
769 let mut in_idx: usize = 0;
770 let mut out_idx: usize = 0;
771 loop {
772 let mut in_end = in_idx + step;
773 if in_end > n {
774 in_end = n;
775 }
776 let written = updater(
777 &mut encrypting_key,
778 &plaintext[in_idx..in_end],
779 &mut ciphertext,
780 out_idx,
781 block_len,
782 step,
783 );
784 in_idx += step;
785 out_idx += written;
786 if in_idx >= n {
787 break;
788 }
789 }
790 let out_end = out_idx + block_len;
791 ciphertext[out_end..].fill(canary);
792 let (decrypt_iv, written_len) = {
793 let (decrypt_iv, output) = encrypting_key
794 .finish(&mut ciphertext[out_idx..out_end])
795 .unwrap();
796 (decrypt_iv, output.written().len())
797 };
798 assert_no_write_past(&ciphertext, out_idx, out_end, canary);
799 ciphertext.truncate(out_idx + written_len);
800 match mode {
801 OperatingMode::CBC | OperatingMode::ECB => {
802 assert!(ciphertext.len() > plaintext.len());
803 assert!(ciphertext.len() <= plaintext.len() + block_len);
804 }
805 _ => {
806 assert_eq!(ciphertext.len(), plaintext.len());
807 }
808 }
809
810 (ciphertext.into_boxed_slice(), decrypt_iv)
811 }
812
813 fn step_decrypt_with_updater<F>(
817 mut decrypting_key: StreamingDecryptingKey,
818 ciphertext: &[u8],
819 step: usize,
820 canary: u8,
821 mut updater: F,
822 ) -> Box<[u8]>
823 where
824 F: FnMut(&mut StreamingDecryptingKey, &[u8], &mut [u8], usize, usize, usize) -> usize,
825 {
826 let alg = decrypting_key.algorithm();
827 let mode = decrypting_key.mode();
828 let block_len = alg.block_len();
829 let n = ciphertext.len();
830 let mut plaintext = vec![canary; n + 2 * block_len];
831
832 let mut in_idx: usize = 0;
833 let mut out_idx: usize = 0;
834 loop {
835 let mut in_end = in_idx + step;
836 if in_end > n {
837 in_end = n;
838 }
839 let written = updater(
840 &mut decrypting_key,
841 &ciphertext[in_idx..in_end],
842 &mut plaintext,
843 out_idx,
844 block_len,
845 step,
846 );
847 in_idx += step;
848 out_idx += written;
849 if in_idx >= n {
850 break;
851 }
852 }
853 let out_end = out_idx + block_len;
854 plaintext[out_end..].fill(canary);
855 let written_len = {
856 let output = decrypting_key
857 .finish(&mut plaintext[out_idx..out_end])
858 .unwrap();
859 output.written().len()
860 };
861 assert_no_write_past(&plaintext, out_idx, out_end, canary);
862 plaintext.truncate(out_idx + written_len);
863 match mode {
864 OperatingMode::CBC | OperatingMode::ECB => {
865 assert!(ciphertext.len() > plaintext.len());
866 assert!(ciphertext.len() <= plaintext.len() + block_len);
867 }
868 _ => {
869 assert_eq!(ciphertext.len(), plaintext.len());
870 }
871 }
872 plaintext.into_boxed_slice()
873 }
874
875 fn step_encrypt(
876 encrypting_key: StreamingEncryptingKey,
877 plaintext: &[u8],
878 step: usize,
879 canary: u8,
880 ) -> (Box<[u8]>, DecryptionContext) {
881 step_encrypt_with_updater(
882 encrypting_key,
883 plaintext,
884 step,
885 canary,
886 |key, input, output, out_idx, block_len, _step| {
887 let out_end = out_idx + input.len() + block_len - 1;
888 apply_update_with_canary(output, out_idx, out_end, canary, |out| {
889 key.update(input, out).unwrap().written().len()
890 })
891 },
892 )
893 }
894
895 fn step_decrypt(
896 decrypting_key: StreamingDecryptingKey,
897 ciphertext: &[u8],
898 step: usize,
899 canary: u8,
900 ) -> Box<[u8]> {
901 step_decrypt_with_updater(
902 decrypting_key,
903 ciphertext,
904 step,
905 canary,
906 |key, input, output, out_idx, block_len, _step| {
907 let out_end = out_idx + input.len() + block_len - 1;
908 apply_update_with_canary(output, out_idx, out_end, canary, |out| {
909 key.update(input, out).unwrap().written().len()
910 })
911 },
912 )
913 }
914
915 fn less_safe_min_out(block_len: usize, out_idx: usize, input_len: usize) -> usize {
916 let next_total = out_idx + input_len;
917 input_len + ((block_len - (next_total % block_len)) % block_len)
918 }
919
920 fn step_encrypt_less_safe(
921 encrypting_key: StreamingEncryptingKey,
922 plaintext: &[u8],
923 step: usize,
924 canary: u8,
925 ) -> (Box<[u8]>, DecryptionContext) {
926 step_encrypt_with_updater(
927 encrypting_key,
928 plaintext,
929 step,
930 canary,
931 |key, input, output, out_idx, block_len, step| {
932 let min_out_len = less_safe_min_out(block_len, out_idx, input.len());
933 if input.len() % block_len == 0 && step % block_len == 0 {
934 assert_eq!(input.len(), min_out_len);
936 }
937 let out_end = out_idx + min_out_len;
938 apply_update_with_canary(output, out_idx, out_end, canary, |out| {
939 key.less_safe_update(input, out).unwrap().written().len()
940 })
941 },
942 )
943 }
944
945 fn step_decrypt_less_safe(
946 decrypting_key: StreamingDecryptingKey,
947 ciphertext: &[u8],
948 step: usize,
949 canary: u8,
950 ) -> Box<[u8]> {
951 step_decrypt_with_updater(
952 decrypting_key,
953 ciphertext,
954 step,
955 canary,
956 |key, input, output, out_idx, block_len, step| {
957 let min_out_len = less_safe_min_out(block_len, out_idx, input.len());
958 if input.len() % block_len == 0 && step % block_len == 0 {
959 assert_eq!(input.len(), min_out_len);
961 }
962 let out_end = out_idx + min_out_len;
963 apply_update_with_canary(output, out_idx, out_end, canary, |out| {
964 key.less_safe_update(input, out).unwrap().written().len()
965 })
966 },
967 )
968 }
969
970 macro_rules! helper_stream_step_encrypt_test {
971 ($mode:ident) => {
972 paste! {
973 fn [<helper_test_ $mode _stream_encrypt_step_n_bytes>](
974 encrypting_key_creator: impl Fn() -> StreamingEncryptingKey,
975 decrypting_key_creator: impl Fn(DecryptionContext) -> StreamingDecryptingKey,
976 n: usize,
977 step: usize,
978 canary: u8,
979 ) {
980 let mut input = vec![0u8; n];
981 let random = SystemRandom::new();
982 random.fill(&mut input).unwrap();
983
984 let encrypting_key = encrypting_key_creator();
985
986 let (ciphertext, decrypt_iv) =
987 step_encrypt(encrypting_key, &input, step, canary);
988
989 let decrypting_key = decrypting_key_creator(decrypt_iv);
990
991 let plaintext = step_decrypt(decrypting_key, &ciphertext, step, canary);
992
993 assert_eq!(input.as_slice(), &*plaintext);
994 }
995 }
996 };
997 ($mode:ident, less_safe) => {
998 paste! {
999 fn [<helper_test_ $mode _stream_encrypt_step_n_bytes_less_safe>](
1000 encrypting_key_creator: impl Fn() -> StreamingEncryptingKey,
1001 decrypting_key_creator: impl Fn(DecryptionContext) -> StreamingDecryptingKey,
1002 n: usize,
1003 step: usize,
1004 canary: u8,
1005 ) {
1006 let mut input = vec![0u8; n];
1007 let random = SystemRandom::new();
1008 random.fill(&mut input).unwrap();
1009
1010 let encrypting_key = encrypting_key_creator();
1011
1012 let (ciphertext, decrypt_iv) =
1013 step_encrypt_less_safe(encrypting_key, &input, step, canary);
1014
1015 let decrypting_key = decrypting_key_creator(decrypt_iv);
1016
1017 let plaintext =
1018 step_decrypt_less_safe(decrypting_key, &ciphertext, step, canary);
1019
1020 assert_eq!(input.as_slice(), &*plaintext);
1021 }
1022 }
1023 };
1024 }
1025
1026 helper_stream_step_encrypt_test!(cbc_pkcs7);
1027 helper_stream_step_encrypt_test!(ctr);
1028 helper_stream_step_encrypt_test!(cfb128);
1029 helper_stream_step_encrypt_test!(ecb_pkcs7);
1030
1031 helper_stream_step_encrypt_test!(cbc_pkcs7, less_safe);
1032 helper_stream_step_encrypt_test!(ctr, less_safe);
1033 helper_stream_step_encrypt_test!(cfb128, less_safe);
1034 helper_stream_step_encrypt_test!(ecb_pkcs7, less_safe);
1035
1036 fn run_step_matrix(test: impl Fn(usize, usize)) {
1037 for i in 13..=21 {
1038 for j in 124..=131 {
1039 test(j, i);
1040 test(j, j - i);
1041 }
1042 }
1043 for j in 124..=131 {
1044 test(j, j);
1045 test(j, 256);
1046 test(j, 1);
1047 }
1048 }
1049
1050 fn random_aes_key(len: usize) -> Vec<u8> {
1051 let mut key = vec![0u8; len];
1052 SystemRandom::new().fill(&mut key).unwrap();
1053 key
1054 }
1055
1056 macro_rules! step_roundtrip_tests {
1057 ($name:ident, $constructor:ident, $helper:ident) => {
1058 #[test]
1059 fn $name() {
1060 for (alg, key_len) in [(&AES_128, AES_128_KEY_LEN), (&AES_256, AES_256_KEY_LEN)] {
1061 let key = random_aes_key(key_len);
1062 let encrypting_key_creator = || {
1063 let key = UnboundCipherKey::new(alg, &key).unwrap();
1064 StreamingEncryptingKey::$constructor(key).unwrap()
1065 };
1066 let decrypting_key_creator = |decryption_ctx: DecryptionContext| {
1067 let key = UnboundCipherKey::new(alg, &key).unwrap();
1068 StreamingDecryptingKey::$constructor(key, decryption_ctx).unwrap()
1069 };
1070 run_step_matrix(|n, step| {
1074 let canary = OUTPUT_CANARIES[(n + step) % OUTPUT_CANARIES.len()];
1075 $helper(
1076 encrypting_key_creator,
1077 decrypting_key_creator,
1078 n,
1079 step,
1080 canary,
1081 );
1082 });
1083 }
1084 }
1085 };
1086 }
1087
1088 step_roundtrip_tests!(
1089 test_step_cbc,
1090 cbc_pkcs7,
1091 helper_test_cbc_pkcs7_stream_encrypt_step_n_bytes
1092 );
1093 step_roundtrip_tests!(
1094 test_step_ctr,
1095 ctr,
1096 helper_test_ctr_stream_encrypt_step_n_bytes
1097 );
1098 step_roundtrip_tests!(
1099 test_step_cfb128,
1100 cfb128,
1101 helper_test_cfb128_stream_encrypt_step_n_bytes
1102 );
1103 step_roundtrip_tests!(
1104 test_step_ecb_pkcs7,
1105 ecb_pkcs7,
1106 helper_test_ecb_pkcs7_stream_encrypt_step_n_bytes
1107 );
1108 step_roundtrip_tests!(
1109 test_step_cbc_less_safe,
1110 cbc_pkcs7,
1111 helper_test_cbc_pkcs7_stream_encrypt_step_n_bytes_less_safe
1112 );
1113 step_roundtrip_tests!(
1114 test_step_ctr_less_safe,
1115 ctr,
1116 helper_test_ctr_stream_encrypt_step_n_bytes_less_safe
1117 );
1118 step_roundtrip_tests!(
1119 test_step_cfb128_less_safe,
1120 cfb128,
1121 helper_test_cfb128_stream_encrypt_step_n_bytes_less_safe
1122 );
1123 step_roundtrip_tests!(
1124 test_step_ecb_pkcs7_less_safe,
1125 ecb_pkcs7,
1126 helper_test_ecb_pkcs7_stream_encrypt_step_n_bytes_less_safe
1127 );
1128
1129 #[derive(Clone, Copy)]
1130 enum UpdateVariant {
1131 Documented,
1133 LessSafe,
1135 }
1136
1137 fn assert_block_aligned_updates_stay_in_slice(
1142 mut key: StreamingDecryptingKey,
1143 variant: UpdateVariant,
1144 chunks: usize,
1145 canary: u8,
1146 ) {
1147 let block_len = key.algorithm().block_len();
1148 let ciphertext = vec![0x42u8; chunks * block_len];
1149 let mut output = vec![canary; ciphertext.len() + 3 * block_len];
1152 let mut out_idx = 0usize;
1153
1154 for chunk in ciphertext.chunks(block_len) {
1155 let min_outsize = match variant {
1156 UpdateVariant::Documented => chunk.len() + block_len - 1,
1157 UpdateVariant::LessSafe => less_safe_min_out(block_len, out_idx, chunk.len()),
1158 };
1159 let out_end = out_idx + min_outsize;
1160 out_idx += apply_update_with_canary(&mut output, out_idx, out_end, canary, |out| {
1161 match variant {
1162 UpdateVariant::Documented => key.update(chunk, out),
1163 UpdateVariant::LessSafe => key.less_safe_update(chunk, out),
1164 }
1165 .expect("update rejected a documented-minimum output slice")
1166 .written()
1167 .len()
1168 });
1169 }
1170 }
1171
1172 const REGRESSION_CHUNKS: usize = 4;
1175
1176 macro_rules! decrypt_output_bounds_tests {
1177 ($name:ident, $alg:expr, $key_len:expr, $constructor:ident, $context:expr) => {
1178 paste! {
1179 #[test]
1180 fn [<test_ $name _update_stays_in_output_slice>]() {
1181 for canary in OUTPUT_CANARIES {
1182 let unbound =
1183 UnboundCipherKey::new($alg, &random_aes_key($key_len)).unwrap();
1184 let key =
1185 StreamingDecryptingKey::$constructor(unbound, $context).unwrap();
1186 assert_block_aligned_updates_stay_in_slice(
1187 key,
1188 UpdateVariant::Documented,
1189 REGRESSION_CHUNKS,
1190 canary,
1191 );
1192 }
1193 }
1194
1195 #[test]
1196 fn [<test_ $name _less_safe_update_stays_in_output_slice>]() {
1197 for canary in OUTPUT_CANARIES {
1198 let unbound =
1199 UnboundCipherKey::new($alg, &random_aes_key($key_len)).unwrap();
1200 let key =
1201 StreamingDecryptingKey::$constructor(unbound, $context).unwrap();
1202 assert_block_aligned_updates_stay_in_slice(
1203 key,
1204 UpdateVariant::LessSafe,
1205 REGRESSION_CHUNKS,
1206 canary,
1207 );
1208 }
1209 }
1210 }
1211 };
1212 }
1213
1214 decrypt_output_bounds_tests!(
1215 aes_128_cbc_pkcs7,
1216 &AES_128,
1217 AES_128_KEY_LEN,
1218 cbc_pkcs7,
1219 DecryptionContext::Iv128(FixedLength::from([0u8; IV_LEN_128_BIT]))
1220 );
1221 decrypt_output_bounds_tests!(
1222 aes_256_cbc_pkcs7,
1223 &AES_256,
1224 AES_256_KEY_LEN,
1225 cbc_pkcs7,
1226 DecryptionContext::Iv128(FixedLength::from([0u8; IV_LEN_128_BIT]))
1227 );
1228 decrypt_output_bounds_tests!(
1229 aes_128_ecb_pkcs7,
1230 &AES_128,
1231 AES_128_KEY_LEN,
1232 ecb_pkcs7,
1233 DecryptionContext::None
1234 );
1235 decrypt_output_bounds_tests!(
1236 aes_256_ecb_pkcs7,
1237 &AES_256,
1238 AES_256_KEY_LEN,
1239 ecb_pkcs7,
1240 DecryptionContext::None
1241 );
1242
1243 macro_rules! streaming_cipher_kat {
1244 ($name:ident, $alg:expr, $mode:expr, $key:literal, $iv: literal, $plaintext:literal, $ciphertext:literal, $from_step:literal, $to_step:literal) => {
1245 #[test]
1246 fn $name() {
1247 let key = from_hex($key).unwrap();
1248 let input = from_hex($plaintext).unwrap();
1249 let expected_ciphertext = from_hex($ciphertext).unwrap();
1250 let iv = from_hex($iv).unwrap();
1251
1252 for step in ($from_step..=$to_step) {
1253 let ec = EncryptionContext::Iv128(
1254 FixedLength::<IV_LEN_128_BIT>::try_from(iv.as_slice()).unwrap(),
1255 );
1256
1257 let unbound_key = UnboundCipherKey::new($alg, &key).unwrap();
1258
1259 let encrypting_key =
1260 StreamingEncryptingKey::new(unbound_key, $mode, ec).unwrap();
1261
1262 let (ciphertext, decrypt_ctx) =
1263 step_encrypt(encrypting_key, &input, step, OUTPUT_CANARIES[0]);
1264
1265 assert_eq!(expected_ciphertext.as_slice(), ciphertext.as_ref());
1266
1267 let unbound_key2 = UnboundCipherKey::new($alg, &key).unwrap();
1268 let decrypting_key =
1269 StreamingDecryptingKey::new(unbound_key2, $mode, decrypt_ctx).unwrap();
1270
1271 let plaintext =
1272 step_decrypt(decrypting_key, &ciphertext, step, OUTPUT_CANARIES[1]);
1273 assert_eq!(input.as_slice(), plaintext.as_ref());
1274 }
1275 }
1276 };
1277 ($name:ident, $alg:expr, $mode:expr, $key:literal, $plaintext:literal, $ciphertext:literal, $from_step:literal, $to_step:literal) => {
1278 #[test]
1279 fn $name() {
1280 let key = from_hex($key).unwrap();
1281 let input = from_hex($plaintext).unwrap();
1282 let expected_ciphertext = from_hex($ciphertext).unwrap();
1283
1284 for step in ($from_step..=$to_step) {
1285 let unbound_key = UnboundCipherKey::new($alg, &key).unwrap();
1286
1287 let encrypting_key =
1288 StreamingEncryptingKey::new(unbound_key, $mode, EncryptionContext::None)
1289 .unwrap();
1290
1291 let (ciphertext, decrypt_ctx) =
1292 step_encrypt(encrypting_key, &input, step, OUTPUT_CANARIES[0]);
1293
1294 assert_eq!(expected_ciphertext.as_slice(), ciphertext.as_ref());
1295
1296 let unbound_key2 = UnboundCipherKey::new($alg, &key).unwrap();
1297 let decrypting_key =
1298 StreamingDecryptingKey::new(unbound_key2, $mode, decrypt_ctx).unwrap();
1299
1300 let plaintext =
1301 step_decrypt(decrypting_key, &ciphertext, step, OUTPUT_CANARIES[1]);
1302 assert_eq!(input.as_slice(), plaintext.as_ref());
1303 }
1304 }
1305 };
1306 }
1307
1308 streaming_cipher_kat!(
1309 test_iv_aes_128_ctr_16_bytes,
1310 &AES_128,
1311 OperatingMode::CTR,
1312 "000102030405060708090a0b0c0d0e0f",
1313 "00000000000000000000000000000000",
1314 "00112233445566778899aabbccddeeff",
1315 "c6b01904c3da3df5e7d62bd96d153686",
1316 2,
1317 9
1318 );
1319 streaming_cipher_kat!(
1320 test_iv_aes_256_ctr_15_bytes,
1321 &AES_256,
1322 OperatingMode::CTR,
1323 "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
1324 "00000000000000000000000000000000",
1325 "00112233445566778899aabbccddee",
1326 "f28122856e1cf9a7216a30d111f399",
1327 2,
1328 9
1329 );
1330
1331 streaming_cipher_kat!(
1332 test_openssl_aes_128_ctr_15_bytes,
1333 &AES_128,
1334 OperatingMode::CTR,
1335 "244828580821c1652582c76e34d299f5",
1336 "093145d5af233f46072a5eb5adc11aa1",
1337 "3ee38cec171e6cf466bf0df98aa0e1",
1338 "bd7d928f60e3422d96b3f8cd614eb2",
1339 2,
1340 9
1341 );
1342
1343 streaming_cipher_kat!(
1344 test_openssl_aes_256_ctr_15_bytes,
1345 &AES_256,
1346 OperatingMode::CTR,
1347 "0857db8240ea459bdf660b4cced66d1f2d3734ff2de7b81e92740e65e7cc6a1d",
1348 "f028ecb053f801102d11fccc9d303a27",
1349 "eca7285d19f3c20e295378460e8729",
1350 "b5098e5e788de6ac2f2098eb2fc6f8",
1351 2,
1352 9
1353 );
1354
1355 streaming_cipher_kat!(
1356 test_iv_aes_128_cbc_16_bytes,
1357 &AES_128,
1358 OperatingMode::CBC,
1359 "000102030405060708090a0b0c0d0e0f",
1360 "00000000000000000000000000000000",
1361 "00112233445566778899aabbccddeeff",
1362 "69c4e0d86a7b0430d8cdb78070b4c55a9e978e6d16b086570ef794ef97984232",
1363 2,
1364 9
1365 );
1366
1367 streaming_cipher_kat!(
1368 test_iv_aes_256_cbc_15_bytes,
1369 &AES_256,
1370 OperatingMode::CBC,
1371 "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
1372 "00000000000000000000000000000000",
1373 "00112233445566778899aabbccddee",
1374 "2ddfb635a651a43f582997966840ca0c",
1375 2,
1376 9
1377 );
1378
1379 streaming_cipher_kat!(
1380 test_openssl_aes_128_cbc_15_bytes,
1381 &AES_128,
1382 OperatingMode::CBC,
1383 "053304bb3899e1d99db9d29343ea782d",
1384 "b5313560244a4822c46c2a0c9d0cf7fd",
1385 "a3e4c990356c01f320043c3d8d6f43",
1386 "ad96993f248bd6a29760ec7ccda95ee1",
1387 2,
1388 9
1389 );
1390
1391 streaming_cipher_kat!(
1392 test_openssl_aes_128_cbc_16_bytes,
1393 &AES_128,
1394 OperatingMode::CBC,
1395 "95af71f1c63e4a1d0b0b1a27fb978283",
1396 "89e40797dca70197ff87d3dbb0ef2802",
1397 "aece7b5e3c3df1ffc9802d2dfe296dc7",
1398 "301b5dab49fb11e919d0d39970d06739301919743304f23f3cbc67d28564b25b",
1399 2,
1400 9
1401 );
1402
1403 streaming_cipher_kat!(
1404 test_openssl_aes_256_cbc_15_bytes,
1405 &AES_256,
1406 OperatingMode::CBC,
1407 "d369e03e9752784917cc7bac1db7399598d9555e691861d9dd7b3292a693ef57",
1408 "1399bb66b2f6ad99a7f064140eaaa885",
1409 "7385f5784b85bf0a97768ddd896d6d",
1410 "4351082bac9b4593ae8848cc9dfb5a01",
1411 2,
1412 9
1413 );
1414
1415 streaming_cipher_kat!(
1416 test_openssl_aes_256_cbc_16_bytes,
1417 &AES_256,
1418 OperatingMode::CBC,
1419 "d4a8206dcae01242f9db79a4ecfe277d0f7bb8ccbafd8f9809adb39f35aa9b41",
1420 "24f6076548fb9d93c8f7ed9f6e661ef9",
1421 "a39c1fdf77ea3e1f18178c0ec237c70a",
1422 "f1af484830a149ee0387b854d65fe87ca0e62efc1c8e6909d4b9ab8666470453",
1423 2,
1424 9
1425 );
1426
1427 streaming_cipher_kat!(
1428 test_openssl_aes_128_cfb128_16_bytes,
1429 &AES_128,
1430 OperatingMode::CFB128,
1431 "5c353f739429bbd48b7e3f9a76facf4d",
1432 "7b2c7ce17a9b6a59a9e64253b98c8cd1",
1433 "add1bcebeaabe9423d4e916400e877c5",
1434 "8440ec442e4135a613ddb2ce26107e10",
1435 2,
1436 9
1437 );
1438
1439 streaming_cipher_kat!(
1440 test_openssl_aes_128_cfb128_15_bytes,
1441 &AES_128,
1442 OperatingMode::CFB128,
1443 "e1f39d70ad378efc1ac318aa8ac4489f",
1444 "ec78c3d54fff2fe09678c7883024ddce",
1445 "b8c905004b2a92a323769f1b8dc1b2",
1446 "964c3e9bf8bf2a3cca02d8e2e75608",
1447 2,
1448 9
1449 );
1450
1451 streaming_cipher_kat!(
1452 test_openssl_aes_256_cfb128_16_bytes,
1453 &AES_256,
1454 OperatingMode::CFB128,
1455 "0e8117d0984d6acb957a5d6ca526a12fa612ce5de2daadebd42c14d28a0a192e",
1456 "09147a153b230a40cd7bf4197ad0e825",
1457 "13f4540a4e06394148ade31a6f678787",
1458 "250e590e47b7613b7d0a53f684e970d6",
1459 2,
1460 9
1461 );
1462
1463 streaming_cipher_kat!(
1464 test_openssl_aes_256_cfb128_15_bytes,
1465 &AES_256,
1466 OperatingMode::CFB128,
1467 "5cb17d8d5b9dbd81e4f1e0a2c82ebf36cf61156388fb7abf99d4526622858225",
1468 "13c77415ec24f3e2f784f228478a85be",
1469 "3efa583df4405aab61e18155aa7e0d",
1470 "c1f2ffe8aa5064199e8f4f1b388303",
1471 2,
1472 9
1473 );
1474
1475 streaming_cipher_kat!(
1476 test_openssl_aes_128_ecb_pkcs7_16_bytes,
1477 &AES_128,
1478 OperatingMode::ECB,
1479 "a1b7cd124f9824a1532d8440f8136788",
1480 "388118e6848b0cea97401707a754d7a1",
1481 "19b7c7f5d9c2bda3f957e9e7d20847828d5eb5624bcbf221014063a87b38d133",
1482 2,
1483 9
1484 );
1485
1486 streaming_cipher_kat!(
1487 test_openssl_aes_128_ecb_pkcs7_15_bytes,
1488 &AES_128,
1489 OperatingMode::ECB,
1490 "d10e12accb837aaffbb284448e53138c",
1491 "b21cfd1c9e6e7e6e912c82c7dd1aa8",
1492 "3d1168e61df34b51c6ab6745c20ee881",
1493 2,
1494 9
1495 );
1496
1497 streaming_cipher_kat!(
1498 test_openssl_aes_256_ecb_pkcs7_16_bytes,
1499 &AES_256,
1500 OperatingMode::ECB,
1501 "0600f4ad4eda4bc8e3e99592abdfce7eb08fee0ccc801c5ccee26134bcaafbbd",
1502 "516b45cb1342239a549bd8c1d5998f98",
1503 "854c593555a213e4a862c6f66aa4a79631faca131eba6f163e5cd3940e9c0a57",
1504 2,
1505 9
1506 );
1507
1508 streaming_cipher_kat!(
1509 test_openssl_aes_256_ecb_pkcs7_15_bytes,
1510 &AES_256,
1511 OperatingMode::ECB,
1512 "80f235756c8f70094ae1f99a95a599c27c4452a4b8412fd934e2b253f7098508",
1513 "2235590b90190d7a1dc2464a0205ad",
1514 "8547d8ac8dc6d9cebb2dc77a7034bb67",
1515 2,
1516 9
1517 );
1518}