From 5e34bc4404e111d94db0ab68b9996246f5d105f9 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Sat, 4 Nov 2023 20:39:03 +0000 Subject: [PATCH] Add an option to in-place decrypt with `ChaCha20Poly1305` In the next commit we'll use this to avoid an allocation when deserializing messages from the wire. --- lightning/src/util/chacha20poly1305rfc.rs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/lightning/src/util/chacha20poly1305rfc.rs b/lightning/src/util/chacha20poly1305rfc.rs index a5bec2c8..d5792e0a 100644 --- a/lightning/src/util/chacha20poly1305rfc.rs +++ b/lightning/src/util/chacha20poly1305rfc.rs @@ -122,10 +122,15 @@ mod real_chachapoly { } } - // Decrypt in place, without checking the tag. Use `finish_and_check_tag` to check it - // later when decryption finishes. - // - // Should never be `pub` because the public API should always enforce tag checking. + pub fn check_decrypt_in_place(&mut self, input_output: &mut [u8], tag: &[u8]) -> Result<(), ()> { + self.decrypt_in_place(input_output); + if self.finish_and_check_tag(tag) { Ok(()) } else { Err(()) } + } + + /// Decrypt in place, without checking the tag. Use `finish_and_check_tag` to check it + /// later when decryption finishes. + /// + /// Should never be `pub` because the public API should always enforce tag checking. pub(super) fn decrypt_in_place(&mut self, input_output: &mut [u8]) { debug_assert!(self.finished == false); self.mac.input(input_output); @@ -133,8 +138,8 @@ mod real_chachapoly { self.cipher.process_in_place(input_output); } - // If we were previously decrypting with `decrypt_in_place`, this method must be used to finish - // decrypting and check the tag. Returns whether or not the tag is valid. + /// If we were previously decrypting with `just_decrypt_in_place`, this method must be used + /// to check the tag. Returns whether or not the tag is valid. pub(super) fn finish_and_check_tag(&mut self, tag: &[u8]) -> bool { debug_assert!(self.finished == false); self.finished = true; @@ -313,6 +318,11 @@ mod fuzzy_chachapoly { true } + pub fn check_decrypt_in_place(&mut self, input_output: &mut [u8], tag: &[u8]) -> Result<(), ()> { + self.decrypt_in_place(input_output); + if self.finish_and_check_tag(tag) { Ok(()) } else { Err(()) } + } + pub(super) fn decrypt_in_place(&mut self, _input: &mut [u8]) { assert!(self.finished == false); } -- 2.30.2