From 6eb2ab19b8f6f612eb1897146c61280cb8371b54 Mon Sep 17 00:00:00 2001 From: Wiktor Kwapisiewicz Date: Tue, 20 Dec 2022 13:33:09 +0100 Subject: [PATCH] Expose `Cipher::cipher_final_unchecked` This mirrors the `Cipher::cipher_update_unchecked` API call for clients that want to manually track the state of internal OpenSSL cipher buffer size. --- openssl/src/cipher_ctx.rs | 44 +++++++++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/openssl/src/cipher_ctx.rs b/openssl/src/cipher_ctx.rs index 08469667af..2fbb19bde6 100644 --- a/openssl/src/cipher_ctx.rs +++ b/openssl/src/cipher_ctx.rs @@ -621,19 +621,41 @@ impl CipherCtxRef { /// Panics if `output` is smaller than the cipher's block size. #[corresponds(EVP_CipherFinal)] pub fn cipher_final(&mut self, output: &mut [u8]) -> Result { - let block_size = self.block_size(); - if block_size > 1 { - assert!(output.len() >= block_size); - } + let min_output_size = self.minimal_output_size(0 /* no input */); + assert!( + output.len() >= min_output_size, + "Output buffer size should be at least {} bytes.", + min_output_size + ); + unsafe { self.cipher_final_unchecked(output) } + } + + /// Finalizes the encryption or decryption process. + /// + /// Any remaining data will be written to the output buffer. + /// + /// Returns the number of bytes written to `output`. + /// + /// This function is the same as [`Self::cipher_final`] but with + /// the output buffer size check removed. + /// + /// SAFETY: The caller is expected to provide `output` buffer + /// large enough to contain correct number of bytes. For streaming + /// ciphers the output buffer can be empty, for block ciphers the + /// output buffer should be at least as big as the block. + #[corresponds(EVP_CipherFinal)] + pub unsafe fn cipher_final_unchecked( + &mut self, + output: &mut [u8], + ) -> Result { let mut outl = 0; - unsafe { - cvt(ffi::EVP_CipherFinal( - self.as_ptr(), - output.as_mut_ptr(), - &mut outl, - ))?; - } + + cvt(ffi::EVP_CipherFinal( + self.as_ptr(), + output.as_mut_ptr(), + &mut outl, + ))?; Ok(outl as usize) }