Skip to main content

aws_lc_rs/cipher/
streaming.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0 OR ISC
3
4use 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
19/// A key for streaming encryption operations.
20pub 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
30/// A struct indicating the portion of a buffer written to, and/or not written to, during an
31/// encryption/decryption operation.
32pub 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    /// Returns the slice from the buffer that was modified by the operation.
46    #[must_use]
47    pub fn written(&self) -> &[u8] {
48        self.written
49    }
50
51    /// Returns the slice of the buffer that was not modified by the operation.
52    #[must_use]
53    pub fn remainder(&self) -> &[u8] {
54        self.remainder
55    }
56
57    /// Returns a mutable slice of the buffer that was not modified by the operation.
58    #[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    // AWS-LC copies the key and iv values into the EVP_CIPHER_CTX, and thus can be dropped after this.
77    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    // AWS-LC copies the key and iv values into the EVP_CIPHER_CTX, and thus can be dropped after this.
105    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        // The streaming path passes raw key bytes to the EVP API rather than
132        // going through `SymmetricCipherKey` construction.  Validate
133        // algorithm-specific key constraints (e.g. DES weak-key / K1!=K2
134        // checks) that would otherwise be missed.
135        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    /// Updates the internal state of the key with the provided plaintext `input`,
211    /// potentially writing bytes of ciphertext to `output`.
212    ///
213    /// The number of bytes written to `output` can be up to `input.len()`
214    /// plus the block length of the algorithm (e.g., [`Algorithm::block_len`]) minus one.
215    ///
216    /// # Errors
217    /// * Returns an error if the `output` buffer is smaller than the length of
218    ///   the `input` plus the algorithm's block length (e.g. [`Algorithm::block_len`]) minus one.
219    /// * May return an error if the length of `input` plus the algorithm's block length is larger than `i32::MAX`.
220    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    /// Updates the internal state of the key with the provided plaintext `input`,
235    /// potentially writing bytes of ciphertext to `output`.
236    ///
237    /// This function has looser output buffer size requirements than [`Self::update`],
238    /// calculating the minimum required size based on the total bytes of output generated
239    /// and the cipher's block length. This is considered "less safe" because it's
240    /// based on assumptions about the state of the underlying operations.
241    ///
242    /// The minimum output buffer size is calculated based on how many bytes are needed to
243    /// reach the next block boundary after processing the input. If `next_total` is the sum
244    /// of bytes already generated plus `input.len()`, then the minimum size is:
245    /// `input.len() + ((block_len - (next_total % block_len)) % block_len)`
246    ///
247    /// # Errors
248    /// Returns an error if the `output` buffer is smaller than the calculated minimum size,
249    /// if the total output length overflows, or if the length of `input` is larger than
250    /// `i32::MAX`.
251    ///
252    /// # Panics
253    /// Panics if the number of bytes written by the cipher operation exceeds the output
254    /// buffer length.
255    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    /// Finishes the encryption operation, writing any remaining ciphertext to
275    /// `output`.
276    ///
277    /// The number of bytes written to `output` can be up to the block length of
278    /// [`Algorithm::block_len`].
279    ///
280    /// # Errors
281    /// * Returns an error if the `output` buffer is smaller than the algorithm's
282    ///   block length.
283    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    /// Returns the cipher operating mode.
307    #[must_use]
308    pub fn mode(&self) -> OperatingMode {
309        self.mode
310    }
311
312    /// Returns the cipher algorithm.
313    #[must_use]
314    pub fn algorithm(&self) -> &'static Algorithm {
315        self.algorithm
316    }
317
318    /// Constructs a `StreamingEncryptingKey` for encrypting data using the CTR cipher mode.
319    /// The resulting ciphertext will be the same length as the plaintext.
320    ///
321    /// # Errors
322    /// Returns an error on an internal failure. With `legacy-des` enabled, also
323    /// returned if `key`'s algorithm does not support CTR mode (e.g.
324    /// `DES_FOR_LEGACY_USE_ONLY`, `DES_EDE_FOR_LEGACY_USE_ONLY`,
325    /// `DES_EDE3_FOR_LEGACY_USE_ONLY`).
326    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    /// Constructs a `StreamingEncryptingKey` for encrypting data using the CTR cipher mode.
332    /// The resulting ciphertext will be the same length as the plaintext.
333    ///
334    /// This is considered less safe because the caller could potentially construct
335    /// an `EncryptionContext` from a previously used initialization vector (IV).
336    ///
337    /// # Errors
338    /// Returns an error on an internal failure. With `legacy-des` enabled, also
339    /// returned if `key`'s algorithm does not support CTR mode (e.g.
340    /// `DES_FOR_LEGACY_USE_ONLY`, `DES_EDE_FOR_LEGACY_USE_ONLY`,
341    /// `DES_EDE3_FOR_LEGACY_USE_ONLY`).
342    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    /// Constructs a `StreamingEncryptingKey` for encrypting data using the CBC cipher mode
350    /// with pkcs7 padding.
351    /// The resulting ciphertext will be longer than the plaintext; padding is added
352    /// to fill the next block of ciphertext.
353    ///
354    /// # Errors
355    /// Returns an error on an internal failure. With `legacy-des` enabled, also
356    /// returned if `key` was constructed with `DES_FOR_LEGACY_USE_ONLY`,
357    /// `DES_EDE_FOR_LEGACY_USE_ONLY` or `DES_EDE3_FOR_LEGACY_USE_ONLY` and the
358    /// provided key material contains weak or semi-weak DES subkeys, or (for
359    /// Triple DES) a degenerate subkey configuration (e.g. `K1 == K2` for 2TDEA,
360    /// or any pairwise equality for 3TDEA).
361    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    /// Constructs a `StreamingEncryptingKey` for encrypting data using the CFB128 cipher mode.
367    /// The resulting ciphertext will be the same length as the plaintext.
368    ///
369    /// # Errors
370    /// Returns an error on an internal failure. With `legacy-des` enabled, also
371    /// returned if `key`'s algorithm does not support CFB128 mode (e.g.
372    /// `DES_FOR_LEGACY_USE_ONLY`, `DES_EDE_FOR_LEGACY_USE_ONLY`,
373    /// `DES_EDE3_FOR_LEGACY_USE_ONLY`).
374    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    /// Constructs a `StreamingEncryptingKey` for encrypting using ECB cipher mode with PKCS7 padding.
382    /// The resulting plaintext will be the same length as the ciphertext.
383    ///
384    /// # ☠️ ️️️DANGER ☠️
385    /// Offered for computability purposes only. This is an extremely dangerous mode, and
386    /// very likely not what you want to use.
387    ///
388    /// # Errors
389    /// Returns an error on an internal failure. With `legacy-des` enabled, also
390    /// returned if `key` was constructed with `DES_FOR_LEGACY_USE_ONLY`,
391    /// `DES_EDE_FOR_LEGACY_USE_ONLY` or `DES_EDE3_FOR_LEGACY_USE_ONLY` and the
392    /// provided key material contains weak or semi-weak DES subkeys, or (for
393    /// Triple DES) a degenerate subkey configuration (e.g. `K1 == K2` for 2TDEA,
394    /// or any pairwise equality for 3TDEA).
395    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    /// Constructs a `StreamingEncryptingKey` for encrypting data using the CFB128 cipher mode.
401    /// The resulting ciphertext will be the same length as the plaintext.
402    ///
403    /// This is considered less safe because the caller could potentially construct
404    /// an `EncryptionContext` from a previously used initialization vector (IV).
405    ///
406    /// # Errors
407    /// Returns an error on an internal failure. With `legacy-des` enabled, also
408    /// returned if `key`'s algorithm does not support CFB128 mode (e.g.
409    /// `DES_FOR_LEGACY_USE_ONLY`, `DES_EDE_FOR_LEGACY_USE_ONLY`,
410    /// `DES_EDE3_FOR_LEGACY_USE_ONLY`).
411    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    /// Constructs a `StreamingEncryptingKey` for encrypting data using the CBC cipher mode
419    /// with pkcs7 padding.
420    /// The resulting ciphertext will be longer than the plaintext; padding is added
421    /// to fill the next block of ciphertext.
422    ///
423    /// This is considered less safe because the caller could potentially construct
424    /// an `EncryptionContext` from a previously used initialization vector (IV).
425    ///
426    /// # Errors
427    /// Returns an error on an internal failure. With `legacy-des` enabled, also
428    /// returned if `key` was constructed with `DES_FOR_LEGACY_USE_ONLY`,
429    /// `DES_EDE_FOR_LEGACY_USE_ONLY` or `DES_EDE3_FOR_LEGACY_USE_ONLY` and the
430    /// provided key material contains weak or semi-weak DES subkeys, or (for
431    /// Triple DES) a degenerate subkey configuration (e.g. `K1 == K2` for 2TDEA,
432    /// or any pairwise equality for 3TDEA).
433    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
441/// A key for streaming decryption operations.
442pub 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        // See comment in `StreamingEncryptingKey::new`.
463        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        // Reported length, not bytes written -- so this is not a bounds check on
533        // the write. The canary tests in this module cover that.
534        assert!(outlen <= output.len());
535
536        Ok(BufferUpdate::new(output, outlen))
537    }
538
539    /// Updates the internal state of the key with the provided ciphertext `input`,
540    /// potentially also writing bytes of plaintext to `output`.
541    /// The number of bytes written to `output` can be up to `input.len()`
542    /// plus the block length of the cipher algorithm (e.g., [`Algorithm::block_len`]) minus one.
543    ///
544    /// # Errors
545    /// * Returns an error if the `output` buffer is smaller than the length of
546    ///   the `input` plus the algorithm's block length minus one.
547    /// * May return an error if the length of `input` plus the algorithm's block length is larger
548    ///   than `i32::MAX`.
549    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    /// Updates the internal state of the key with the provided ciphertext `input`,
564    /// potentially writing bytes of plaintext to `output`.
565    ///
566    /// This function has looser output buffer size requirements than [`Self::update`],
567    /// calculating the minimum required size based on the total bytes of output generated
568    /// and the cipher's block length. This is considered "less safe" because it's
569    /// based on assumptions about the state of the underlying operations.
570    ///
571    /// The minimum output buffer size is calculated based on how many bytes are needed to
572    /// reach the next block boundary after processing the input. If `next_total` is the sum
573    /// of bytes already generated plus `input.len()`, then the minimum size is:
574    /// `input.len() + ((block_len - (next_total % block_len)) % block_len)`
575    ///
576    /// # Errors
577    /// Returns an error if the `output` buffer is smaller than the calculated minimum size,
578    /// if the total output length overflows, or if the length of `input` is larger than
579    /// `i32::MAX`.
580    ///
581    /// # Panics
582    /// Panics if the number of bytes written by the cipher operation exceeds the output
583    /// buffer length.
584    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    /// Finishes the decryption operation, writing the remaining plaintext to
604    /// `output`.
605    /// The number of bytes written to `output` can be up to the block length of
606    /// the cipher algorithm (e.g., [`Algorithm::block_len`]).
607    ///
608    /// # Errors
609    /// * Returns an error if the `output` buffer is smaller than the algorithm's
610    ///   block length.
611    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    /// Returns the cipher operating mode.
632    #[must_use]
633    pub fn mode(&self) -> OperatingMode {
634        self.mode
635    }
636
637    /// Returns the cipher algorithm
638    #[must_use]
639    pub fn algorithm(&self) -> &'static Algorithm {
640        self.algorithm
641    }
642
643    /// Constructs a `StreamingDecryptingKey` for decrypting using the CTR cipher mode.
644    /// The resulting plaintext will be the same length as the ciphertext.
645    ///
646    /// # Errors
647    /// Returns an error on an internal failure. With `legacy-des` enabled, also
648    /// returned if `key`'s algorithm does not support CTR mode (e.g.
649    /// `DES_FOR_LEGACY_USE_ONLY`, `DES_EDE_FOR_LEGACY_USE_ONLY`,
650    /// `DES_EDE3_FOR_LEGACY_USE_ONLY`).
651    pub fn ctr(key: UnboundCipherKey, context: DecryptionContext) -> Result<Self, Unspecified> {
652        Self::new(key, OperatingMode::CTR, context)
653    }
654
655    /// Constructs a `StreamingDecryptingKey` for decrypting using the CBC cipher mode.
656    /// The resulting plaintext will be shorter than the ciphertext.
657    ///
658    /// # Errors
659    /// Returns an error on an internal failure. With `legacy-des` enabled, also
660    /// returned if `key` was constructed with `DES_FOR_LEGACY_USE_ONLY`,
661    /// `DES_EDE_FOR_LEGACY_USE_ONLY` or `DES_EDE3_FOR_LEGACY_USE_ONLY` and the
662    /// provided key material contains weak or semi-weak DES subkeys, or (for
663    /// Triple DES) a degenerate subkey configuration (e.g. `K1 == K2` for 2TDEA,
664    /// or any pairwise equality for 3TDEA).
665    pub fn cbc_pkcs7(
666        key: UnboundCipherKey,
667        context: DecryptionContext,
668    ) -> Result<Self, Unspecified> {
669        Self::new(key, OperatingMode::CBC, context)
670    }
671
672    // Constructs a `StreamingDecryptingKey` for decrypting using the CFB128 cipher mode.
673    /// The resulting plaintext will be the same length as the ciphertext.
674    ///
675    /// # Errors
676    /// Returns an error on an internal failure. With `legacy-des` enabled, also
677    /// returned if `key`'s algorithm does not support CFB128 mode (e.g.
678    /// `DES_FOR_LEGACY_USE_ONLY`, `DES_EDE_FOR_LEGACY_USE_ONLY`,
679    /// `DES_EDE3_FOR_LEGACY_USE_ONLY`).
680    pub fn cfb128(key: UnboundCipherKey, context: DecryptionContext) -> Result<Self, Unspecified> {
681        Self::new(key, OperatingMode::CFB128, context)
682    }
683
684    /// Constructs a `StreamingDecryptingKey` for decrypting using the ECB cipher mode.
685    /// The resulting plaintext will be the same length as the ciphertext.
686    ///
687    /// # ☠️ ️️️DANGER ☠️
688    /// Offered for computability purposes only. This is an extremely dangerous mode, and
689    /// very likely not what you want to use.
690    ///
691    /// # Errors
692    /// Returns an error on an internal failure. With `legacy-des` enabled, also
693    /// returned if `key` was constructed with `DES_FOR_LEGACY_USE_ONLY`,
694    /// `DES_EDE_FOR_LEGACY_USE_ONLY` or `DES_EDE3_FOR_LEGACY_USE_ONLY` and the
695    /// provided key material contains weak or semi-weak DES subkeys, or (for
696    /// Triple DES) a degenerate subkey configuration (e.g. `K1 == K2` for 2TDEA,
697    /// or any pairwise equality for 3TDEA).
698    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    // Complementary fills so a stray write matching one canary is caught by
719    // the other. Refilled immediately before each update/finish so a prior
720    // call's (legal) write into a larger slice cannot be mistaken for an
721    // overrun of a later, shorter one.
722    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    /// Generic helper for step encryption that accepts a closure for the update operation.
749    /// The closure receives: (key, input, output_buffer, out_idx, block_len, step)
750    /// and returns the number of bytes written.
751    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        // Extra block so there is always canary past the documented-min slice
766        // (`in_len + block_len - 1`) and past `finish`'s block-sized tail.
767        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    /// Generic helper for step decryption that accepts a closure for the update operation.
814    /// The closure receives: (key, input, output_buffer, out_idx, block_len, step)
815    /// and returns the number of bytes written.
816    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                    // When input is provided one block at a time, no additional space should be needed.
935                    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                    // When input is provided one block at a time, no additional space should be needed.
960                    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                    // Alternate complementary canaries across the (n, step)
1071                    // grid so both fills are exercised without doubling the
1072                    // already-expensive AES-128 x AES-256 matrix.
1073                    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        /// [`StreamingDecryptingKey::update`]: `in_len + block_len - 1`.
1132        Documented,
1133        /// [`StreamingDecryptingKey::less_safe_update`]: `in_len` when aligned.
1134        LessSafe,
1135    }
1136
1137    /// Feeds block-aligned chunks through `key`, handing each call exactly the
1138    /// minimum output slice its API documents, with canary bytes just past it.
1139    /// `update`-only: the overrun precedes any padding check, so the ciphertext
1140    /// is arbitrary and `finish` is never called.
1141    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        // Widest documented minimum is `2 * block_len - 1`, leaving every slice
1150        // >= `block_len + 1` canary bytes -- enough for a full-block overrun.
1151        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    /// The overrun needs a second call: the first leaves the cipher aligned (so
1173    /// AWS-LC buffers a block), the next replays it. Four gives three chances.
1174    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}