From 74f83c941e50bb765b024a7f2829761b77bf7ea7 Mon Sep 17 00:00:00 2001 From: Wiktor Kwapisiewicz Date: Thu, 27 Oct 2022 10:41:08 +0200 Subject: [PATCH] Add `BigNum::copy_from_slice` Unfortunately `BigNum::from_slice` always creates a new BigNum and cannot be used to initialize an already existing BigNum thus it is not possible to have a secure BigNum initialized from a slice. This patch adds the function for overwriting existing BigNum with given slice bytes. Thus the BigNum can be created using `BigNum::new_secure` and then overwritten using `BigNum::copy_from_slice`. --- openssl/src/bn.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs index 5de7f7cb3..d98fec4d0 100644 --- a/openssl/src/bn.rs +++ b/openssl/src/bn.rs @@ -1080,6 +1080,30 @@ impl BigNum { .map(|p| BigNum::from_ptr(p)) } } + + /// Copies data from a slice overwriting what was in the BigNum. + /// + /// This function can be used to copy data from a slice to a + /// [secure BigNum][`BigNum::new_secure`]. + /// + /// # Examples + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let mut bignum = BigNum::new().unwrap(); + /// bignum.copy_from_slice(&[0x12, 0x00, 0x34]).unwrap(); + /// + /// assert_eq!(bignum, BigNum::from_u32(0x120034).unwrap()); + /// ``` + #[corresponds(BN_bin2bn)] + pub fn copy_from_slice(&mut self, n: &[u8]) -> Result<(), ErrorStack> { + unsafe { + assert!(n.len() <= LenType::max_value() as usize); + + cvt_p(ffi::BN_bin2bn(n.as_ptr(), n.len() as LenType, self.0))?; + Ok(()) + } + } } impl fmt::Debug for BigNumRef { -- GitLab