Skip to content

Commit e6ddc40

Browse files
ilammyjyn514
authored andcommitted
boring: BigNumRef::to_vec_padded()
Wrap BN_bn2bin_padded() which comes useful for exporting fixed-length BIGNUMs, more efficient than padding result of to_vec() afterwards. Note that in OpenSSL the function is called BN_bn2binpad() and has a different order of arguments. BoringSSL's BN_bn2bin_padded() also takes the desired length as "size_t".
1 parent 1507689 commit e6ddc40

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

boring/src/bn.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,6 +852,36 @@ impl BigNumRef {
852852
v
853853
}
854854

855+
/// Returns a big-endian byte vector representation of the absolute value of `self` padded
856+
/// to `pad_to` bytes.
857+
///
858+
/// If `pad_to` is less than `self.num_bytes()` then an error is returned.
859+
///
860+
/// `self` can be recreated by using `from_slice`.
861+
///
862+
/// ```
863+
/// # use boring::bn::BigNum;
864+
/// let bn = BigNum::from_u32(0x4543).unwrap();
865+
///
866+
/// let bn_vec = bn.to_vec_padded(4).unwrap();
867+
/// assert_eq!(&bn_vec, &[0, 0, 0x45, 0x43]);
868+
///
869+
/// let r = bn.to_vec_padded(1);
870+
/// assert!(r.is_err());
871+
///
872+
/// let bn = -BigNum::from_u32(0x4543).unwrap();
873+
/// let bn_vec = bn.to_vec_padded(4).unwrap();
874+
/// assert_eq!(&bn_vec, &[0, 0, 0x45, 0x43]);
875+
/// ```
876+
pub fn to_vec_padded(&self, pad_to: usize) -> Result<Vec<u8>, ErrorStack> {
877+
let mut v = Vec::with_capacity(pad_to);
878+
unsafe {
879+
cvt(ffi::BN_bn2bin_padded(v.as_mut_ptr(), pad_to, self.as_ptr()))?;
880+
v.set_len(pad_to);
881+
}
882+
Ok(v)
883+
}
884+
855885
/// Returns a decimal string representation of `self`.
856886
///
857887
/// ```

0 commit comments

Comments
 (0)