Added BigNum::{from_dec_str,from_hex_str}, BN_dec2bn, and BN_hex2bn.

This commit is contained in:
Chris Cole 2014-12-14 10:02:18 -05:00
parent 7a4fbc1567
commit 38682821ad
2 changed files with 38 additions and 3 deletions

View File

@ -81,6 +81,11 @@ pub struct BIGNUM {
pub flags: c_int, pub flags: c_int,
} }
#[repr(C)]
pub struct BIGNUM_PTR {
pub ptr: *mut BIGNUM,
}
pub type CRYPTO_EX_new = extern "C" fn(parent: *mut c_void, ptr: *mut c_void, pub type CRYPTO_EX_new = extern "C" fn(parent: *mut c_void, ptr: *mut c_void,
ad: *const CRYPTO_EX_DATA, idx: c_int, ad: *const CRYPTO_EX_DATA, idx: c_int,
argl: c_long, argp: *const c_void) -> c_int; argl: c_long, argp: *const c_void) -> c_int;
@ -291,9 +296,14 @@ extern "C" {
pub fn BN_bin2bn(s: *const u8, size: c_int, ret: *mut BIGNUM) -> *mut BIGNUM; pub fn BN_bin2bn(s: *const u8, size: c_int, ret: *mut BIGNUM) -> *mut BIGNUM;
pub fn BN_bn2bin(a: *mut BIGNUM, to: *mut u8) -> c_int; pub fn BN_bn2bin(a: *mut BIGNUM, to: *mut u8) -> c_int;
/* Conversion from/to string representation */ /* Conversion from/to decimal string representation */
pub fn BN_dec2bn(a: *mut BIGNUM_PTR, s: *const i8) -> c_int;
pub fn BN_bn2dec(a: *mut BIGNUM) -> *const c_char; pub fn BN_bn2dec(a: *mut BIGNUM) -> *const c_char;
/* Conversion from/to hexidecimal string representation */
pub fn BN_hex2bn(a: *mut BIGNUM_PTR, s: *const i8) -> c_int;
pub fn BN_bn2hex(a: *mut BIGNUM) -> *const c_char;
pub fn CRYPTO_num_locks() -> c_int; pub fn CRYPTO_num_locks() -> c_int;
pub fn CRYPTO_set_locking_callback(func: extern "C" fn(mode: c_int, pub fn CRYPTO_set_locking_callback(func: extern "C" fn(mode: c_int,
n: c_int, n: c_int,

View File

@ -84,8 +84,22 @@ impl BigNum {
}) })
} }
pub fn one() -> BigNum { pub fn from_dec_str(s: &str) -> Result<BigNum, SslError> {
BigNum::new_from(1).unwrap() BigNum::new().and_then(|v| unsafe {
let ref mut bn_ptr = ffi::BIGNUM_PTR { ptr: v.raw(), };
let c_str = s.to_c_str();
try_ssl!(ffi::BN_dec2bn(bn_ptr, c_str.as_ptr()));
Ok(v)
})
}
pub fn from_hex_str(s: &str) -> Result<BigNum, SslError> {
BigNum::new().and_then(|v| unsafe {
let ref mut bn_ptr = ffi::BIGNUM_PTR { ptr: v.raw(), };
let c_str = s.to_c_str();
try_ssl!(ffi::BN_hex2bn(bn_ptr, c_str.as_ptr()));
Ok(v)
})
} }
pub fn new_from_slice(n: &[u8]) -> Result<BigNum, SslError> { pub fn new_from_slice(n: &[u8]) -> Result<BigNum, SslError> {
@ -362,6 +376,17 @@ impl BigNum {
str str
} }
} }
pub fn to_hex_str(&self) -> String {
unsafe {
let buf = ffi::BN_bn2hex(self.raw());
assert!(!buf.is_null());
let c_str = CString::new(buf, false);
let str = c_str.as_str().unwrap().to_string();
ffi::CRYPTO_free(buf as *mut c_void);
str
}
}
} }
impl fmt::Show for BigNum { impl fmt::Show for BigNum {