diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs index 633407eaf0f2c105f06206a8900e3b613c8b4bcd..6b720dca984939e5c638559664db98ee181170b2 100644 --- a/openssl/src/asn1.rs +++ b/openssl/src/asn1.rs @@ -33,7 +33,7 @@ use std::slice; use std::str; use bio::MemBio; -use bn::BigNum; +use bn::{BigNum, BigNumRef}; use error::ErrorStack; use nid::Nid; use string::OpensslString; @@ -191,6 +191,19 @@ foreign_type_and_impl_send_sync! { pub struct Asn1IntegerRef; } +impl Asn1Integer { + /// Converts a bignum to an `Asn1Integer`. + /// + /// Corresponds to [`BN_to_ASN1_INTEGER`]. Also see + /// [`BigNumRef::to_asn1_integer`]. + /// + /// [`BN_to_ASN1_INTEGER`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_to_ASN1_INTEGER.html + /// [`BigNumRef::to_asn1_integer`]: ../bn/struct.BigNumRef.html#method.to_asn1_integer + pub fn from_bn(bn: &BigNumRef) -> Result { + bn.to_asn1_integer() + } +} + impl Asn1IntegerRef { #[allow(missing_docs)] #[deprecated(since = "0.10.6", note = "use to_bn instead")] @@ -306,3 +319,24 @@ cfg_if! { } } } + +#[cfg(test)] +mod tests { + use super::*; + + use bn::BigNum; + + /// Tests conversion between BigNum and Asn1Integer. + #[test] + fn bn_cvt() { + fn roundtrip(bn: BigNum) { + let large = Asn1Integer::from_bn(&bn).unwrap(); + assert_eq!(large.to_bn().unwrap(), bn); + } + + roundtrip(BigNum::from_dec_str("1000000000000000000000000000000000").unwrap()); + roundtrip(-BigNum::from_dec_str("1000000000000000000000000000000000").unwrap()); + roundtrip(BigNum::from_u32(1234).unwrap()); + roundtrip(-BigNum::from_u32(1234).unwrap()); + } +}