Skip to content

Commit

Permalink
boring: BigNumRef::to_vec_padded()
Browse files Browse the repository at this point in the history
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".
  • Loading branch information
ilammy authored and jyn514 committed Feb 12, 2022
1 parent 1507689 commit e6ddc40
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions boring/src/bn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,36 @@ impl BigNumRef {
v
}

/// Returns a big-endian byte vector representation of the absolute value of `self` padded
/// to `pad_to` bytes.
///
/// If `pad_to` is less than `self.num_bytes()` then an error is returned.
///
/// `self` can be recreated by using `from_slice`.
///
/// ```
/// # use boring::bn::BigNum;
/// let bn = BigNum::from_u32(0x4543).unwrap();
///
/// let bn_vec = bn.to_vec_padded(4).unwrap();
/// assert_eq!(&bn_vec, &[0, 0, 0x45, 0x43]);
///
/// let r = bn.to_vec_padded(1);
/// assert!(r.is_err());
///
/// let bn = -BigNum::from_u32(0x4543).unwrap();
/// let bn_vec = bn.to_vec_padded(4).unwrap();
/// assert_eq!(&bn_vec, &[0, 0, 0x45, 0x43]);
/// ```
pub fn to_vec_padded(&self, pad_to: usize) -> Result<Vec<u8>, ErrorStack> {
let mut v = Vec::with_capacity(pad_to);
unsafe {
cvt(ffi::BN_bn2bin_padded(v.as_mut_ptr(), pad_to, self.as_ptr()))?;
v.set_len(pad_to);
}
Ok(v)
}

/// Returns a decimal string representation of `self`.
///
/// ```
Expand Down

0 comments on commit e6ddc40

Please sign in to comment.