From 56d47b757da04bdb4414e350e6438a93242f53c8 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Wed, 8 Apr 2020 03:45:45 -0400 Subject: mlock sensitive memory --- src/cipherstring.rs | 44 +++++++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 11 deletions(-) (limited to 'src/cipherstring.rs') diff --git a/src/cipherstring.rs b/src/cipherstring.rs index 75edec4..9f2c261 100644 --- a/src/cipherstring.rs +++ b/src/cipherstring.rs @@ -51,32 +51,54 @@ impl CipherString { }) } - pub fn decrypt(&self, enc_key: &[u8], mac_key: &[u8]) -> Result> { + pub fn decrypt(&self, keys: &crate::locked::Keys) -> Result> { + let cipher = self.decrypt_common(keys)?; + cipher + .decrypt_vec(&self.ciphertext) + .context(crate::error::Decrypt) + } + + pub fn decrypt_locked( + &self, + keys: &crate::locked::Keys, + ) -> Result { + let mut res = crate::locked::Vec::new(); + res.extend(self.ciphertext.iter().copied()); + let cipher = self.decrypt_common(keys)?; + cipher + .decrypt(res.data_mut()) + .context(crate::error::Decrypt)?; + Ok(res) + } + + fn decrypt_common( + &self, + keys: &crate::locked::Keys, + ) -> Result< + block_modes::Cbc, + > { if self.ty != 2 { unimplemented!() } if let Some(mac) = &self.mac { - let mut digest = hmac::Hmac::::new_varkey(mac_key) - .map_err(|_| Error::InvalidMacKey)?; + let mut digest = + hmac::Hmac::::new_varkey(keys.mac_key()) + .map_err(|_| Error::InvalidMacKey)?; digest.input(&self.iv); digest.input(&self.ciphertext); let calculated_mac = digest.result().code(); - if !macs_equal(mac, &calculated_mac, mac_key)? { + if !macs_equal(mac, &calculated_mac, keys.mac_key())? { return Err(Error::InvalidMac); } } - let cipher = block_modes::Cbc::< + Ok(block_modes::Cbc::< aes::Aes256, block_modes::block_padding::Pkcs7, - >::new_var(enc_key, &self.iv) - .context(crate::error::CreateBlockMode)?; - - cipher - .decrypt_vec(&self.ciphertext) - .context(crate::error::Decrypt) + >::new_var(keys.enc_key(), &self.iv) + .context(crate::error::CreateBlockMode)?) } } -- cgit v1.2.3-54-g00ecf