From 8f89f0bfa98ac69582f22244dae0f5cc923046e1 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 16 Oct 2016 15:54:09 -0700 Subject: Start on error + BN refactor --- openssl/src/asn1.rs | 73 ++++ openssl/src/asn1/mod.rs | 72 ---- openssl/src/bn.rs | 1003 +++++++++++++++++++++++++++++++++++++++++++++ openssl/src/bn/mod.rs | 1037 ----------------------------------------------- openssl/src/dh.rs | 142 +++++++ openssl/src/dh/mod.rs | 142 ------- openssl/src/lib.rs | 28 ++ 7 files changed, 1246 insertions(+), 1251 deletions(-) create mode 100644 openssl/src/asn1.rs delete mode 100644 openssl/src/asn1/mod.rs create mode 100644 openssl/src/bn.rs delete mode 100644 openssl/src/bn/mod.rs create mode 100644 openssl/src/dh.rs delete mode 100644 openssl/src/dh/mod.rs (limited to 'openssl/src') diff --git a/openssl/src/asn1.rs b/openssl/src/asn1.rs new file mode 100644 index 00000000..91f920a3 --- /dev/null +++ b/openssl/src/asn1.rs @@ -0,0 +1,73 @@ +use libc::c_long; +use std::{ptr, fmt}; +use std::marker::PhantomData; +use std::ops::Deref; +use ffi; + +use {cvt, cvt_p}; +use bio::MemBio; +use error::ErrorStack; + +/// Corresponds to the ASN.1 structure Time defined in RFC5280 +pub struct Asn1Time(Asn1TimeRef<'static>); + +impl Asn1Time { + /// Wraps existing ASN1_TIME and takes ownership + pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1Time { + Asn1Time(Asn1TimeRef::from_ptr(handle)) + } + + fn from_period(period: c_long) -> Result { + ffi::init(); + + unsafe { + let handle = try!(cvt_p(ffi::X509_gmtime_adj(ptr::null_mut(), period))); + Ok(Asn1Time::from_ptr(handle)) + } + } + + /// Creates a new time on specified interval in days from now + pub fn days_from_now(days: u32) -> Result { + Asn1Time::from_period(days as c_long * 60 * 60 * 24) + } +} + +impl Deref for Asn1Time { + type Target = Asn1TimeRef<'static>; + + fn deref(&self) -> &Asn1TimeRef<'static> { + &self.0 + } +} + +/// A borrowed Asn1Time +pub struct Asn1TimeRef<'a>(*mut ffi::ASN1_TIME, PhantomData<&'a ()>); + +impl<'a> Asn1TimeRef<'a> { + /// Creates a new `Asn1TimeRef` wrapping the provided handle. + pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1TimeRef<'a> { + Asn1TimeRef(handle, PhantomData) + } + + /// Returns the raw handle + pub fn as_ptr(&self) -> *mut ffi::ASN1_TIME { + self.0 + } +} + +impl<'a> fmt::Display for Asn1TimeRef<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mem_bio = try!(MemBio::new()); + let as_str = unsafe { + try!(cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.0))); + String::from_utf8_unchecked(mem_bio.get_buf().to_owned()) + }; + write!(f, "{}", as_str) + } +} + +impl Drop for Asn1Time { + fn drop(&mut self) { + unsafe { ffi::ASN1_TIME_free(self.as_ptr()) }; + } +} diff --git a/openssl/src/asn1/mod.rs b/openssl/src/asn1/mod.rs deleted file mode 100644 index 1eab9f04..00000000 --- a/openssl/src/asn1/mod.rs +++ /dev/null @@ -1,72 +0,0 @@ -use libc::c_long; -use std::{ptr, fmt}; -use std::marker::PhantomData; -use std::ops::Deref; - -use bio::MemBio; -use ffi; -use error::ErrorStack; - -/// Corresponds to the ASN.1 structure Time defined in RFC5280 -pub struct Asn1Time(Asn1TimeRef<'static>); - -impl Asn1Time { - /// Wraps existing ASN1_TIME and takes ownership - pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1Time { - Asn1Time(Asn1TimeRef::from_ptr(handle)) - } - - fn from_period(period: c_long) -> Result { - ffi::init(); - - unsafe { - let handle = try_ssl_null!(ffi::X509_gmtime_adj(ptr::null_mut(), period)); - Ok(Asn1Time::from_ptr(handle)) - } - } - - /// Creates a new time on specified interval in days from now - pub fn days_from_now(days: u32) -> Result { - Asn1Time::from_period(days as c_long * 60 * 60 * 24) - } -} - -impl Deref for Asn1Time { - type Target = Asn1TimeRef<'static>; - - fn deref(&self) -> &Asn1TimeRef<'static> { - &self.0 - } -} - -/// A borrowed Asn1Time -pub struct Asn1TimeRef<'a>(*mut ffi::ASN1_TIME, PhantomData<&'a ()>); - -impl<'a> Asn1TimeRef<'a> { - /// Creates a new `Asn1TimeRef` wrapping the provided handle. - pub unsafe fn from_ptr(handle: *mut ffi::ASN1_TIME) -> Asn1TimeRef<'a> { - Asn1TimeRef(handle, PhantomData) - } - - /// Returns the raw handle - pub fn as_ptr(&self) -> *mut ffi::ASN1_TIME { - self.0 - } -} - -impl<'a> fmt::Display for Asn1TimeRef<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mem_bio = try!(MemBio::new()); - let as_str = unsafe { - try_ssl!(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.0)); - String::from_utf8_unchecked(mem_bio.get_buf().to_owned()) - }; - write!(f, "{}", as_str) - } -} - -impl Drop for Asn1Time { - fn drop(&mut self) { - unsafe { ffi::ASN1_TIME_free(self.as_ptr()) }; - } -} diff --git a/openssl/src/bn.rs b/openssl/src/bn.rs new file mode 100644 index 00000000..22924e67 --- /dev/null +++ b/openssl/src/bn.rs @@ -0,0 +1,1003 @@ +use ffi; +use libc::{c_int, c_void}; +use std::cmp::Ordering; +use std::ffi::{CStr, CString}; +use std::{fmt, ptr}; +use std::marker::PhantomData; +use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref, DerefMut}; + +use {cvt, cvt_p, cvt_n}; +use error::ErrorStack; + +/// Specifies the desired properties of a randomly generated `BigNum`. +#[derive(Copy, Clone)] +#[repr(C)] +pub enum RNGProperty { + /// The most significant bit of the number is allowed to be 0. + MsbMaybeZero = -1, + /// The MSB should be set to 1. + MsbOne = 0, + /// The two most significant bits of the number will be set to 1, so that the product of two + /// such random numbers will always have `2 * bits` length. + TwoMsbOne = 1, +} + +macro_rules! with_ctx( + ($name:ident, $action:block) => ({ + let $name = ffi::BN_CTX_new(); + if ($name).is_null() { + Err(ErrorStack::get()) + } else { + let r = $action; + ffi::BN_CTX_free($name); + r + } + }); +); + +macro_rules! with_bn( + ($name:ident, $action:block) => ({ + let tmp = BigNum::new(); + match tmp { + Ok($name) => { + if $action { + Ok($name) + } else { + Err(ErrorStack::get()) + } + }, + Err(err) => Err(err), + } + }); +); + +macro_rules! with_bn_in_ctx( + ($name:ident, $ctx_name:ident, $action:block) => ({ + let tmp = BigNum::new(); + match tmp { + Ok($name) => { + let $ctx_name = ffi::BN_CTX_new(); + if ($ctx_name).is_null() { + Err(ErrorStack::get()) + } else { + let r = + if $action { + Ok($name) + } else { + Err(ErrorStack::get()) + }; + ffi::BN_CTX_free($ctx_name); + r + } + }, + Err(err) => Err(err), + } + }); +); + +/// A context object for `BigNum` operations. +pub struct BnCtx(*mut ffi::BN_CTX); + +impl Drop for BnCtx { + fn drop(&mut self) { + unsafe { + ffi::BN_CTX_free(self.0); + } + } +} + +impl BnCtx { + /// Returns a new `BnCtx`. + pub fn new() -> Result { + unsafe { + cvt_p(ffi::BN_CTX_new()).map(BnCtx) + } + } + + /// Places the result of `a²` in `r`. + pub fn sqr(&mut self, r: &mut BigNumRef, a: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_sqr(r.as_ptr(), a.as_ptr(), self.0)).map(|_| ()) + } + } + + /// Places the result of `a mod m` in `r`. + pub fn nnmod(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_nnmod(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) + } + } + + /// Places the result of `(a + b) mod m` in `r`. + pub fn mod_add(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_add(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) + } + } + + /// Places the result of `(a - b) mod m` in `r`. + pub fn mod_sub(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_sub(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) + } + } + + /// Places the result of `(a * b) mod m` in `r`. + pub fn mod_mul(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef) + -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_mul(r.as_ptr(), a.as_ptr(), b.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) + } + } + + /// Places the result of `a² mod m` in `r`. + pub fn mod_sqr(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_sqr(r.as_ptr(), a.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) + } + } + + /// Places the result of `a^p` in `r`. + pub fn exp(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + p: &BigNumRef) -> Result<(), ErrorStack> { + unsafe{ + cvt(ffi::BN_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), self.0)).map(|_| ()) + } + } + + /// Places the result of `a^p mod m` in `r`. + pub fn mod_exp(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + p: &BigNumRef, + m: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_exp(r.as_ptr(), a.as_ptr(), p.as_ptr(), m.as_ptr(), self.0)).map(|_| ()) + } + } + + /// Places the inverse of `a` modulo `n` in `r`. + pub fn mod_inverse(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + n: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt_p(ffi::BN_mod_inverse(r.0, a.0, n.0, self.0)).map(|_| ()) + } + } + + /// Places the greatest common denominator of `a` and `b` in `r`. + pub fn gcd(&mut self, + r: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_gcd(r.0, a.0, b.0, self.0)).map(|_| ()) + } + } + + /// Checks whether `p` is prime. + /// + /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. + /// + /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. + pub fn is_prime(&mut self, p: &BigNumRef, checks: i32) -> Result { + unsafe { + cvt_n(ffi::BN_is_prime_ex(p.0, checks.into(), self.0, ptr::null_mut())).map(|r| r != 0) + } + } + + /// Checks whether `p` is prime with optional trial division. + /// + /// If `do_trial_division` is `true`, first performs trial division by a number of small primes. + /// Then, like `is_prime`, performs a Miller-Rabin probabilistic primality test with `checks` + /// iterations. + /// + /// # Return Value + /// + /// Returns `true` if `p` is prime with an error probability of less than `0.25 ^ checks`. + pub fn is_prime_fasttest(&mut self, + p: &BigNumRef, + checks: i32, + do_trial_division: bool) -> Result { + unsafe { + cvt_n(ffi::BN_is_prime_fasttest_ex(p.0, + checks.into(), + self.0, + do_trial_division as c_int, + ptr::null_mut())) + .map(|r| r != 0) + } + } +} + +/// A borrowed, signed, arbitrary-precision integer. +#[derive(Copy, Clone)] +pub struct BigNumRef<'a>(*mut ffi::BIGNUM, PhantomData<&'a ()>); + +impl<'a> BigNumRef<'a> { + pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNumRef<'a> { + BigNumRef(handle, PhantomData) + } + + /// Adds a `u32` to `self`. + pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_add_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) + } + } + + /// Subtracts a `u32` from `self`. + pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_sub_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) + } + } + + /// Multiplies a `u32` by `self`. + pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mul_word(self.0, w as ffi::BN_ULONG)).map(|_| ()) + } + } + + /// Divides `self` by a `u32`, returning the remainder. + pub fn div_word(&mut self, w: u32) -> Result { + unsafe { + let r = ffi::BN_div_word(self.0, w.into()); + if r == ffi::BN_ULONG::max_value() { + Err(ErrorStack::get()) + } else { + Ok(r.into()) + } + } + } + + /// Returns the result of `self` modulo `w`. + pub fn mod_word(&self, w: u32) -> Result { + unsafe { + let r = ffi::BN_mod_word(self.0, w.into()); + if r == ffi::BN_ULONG::max_value() { + Err(ErrorStack::get()) + } else { + Ok(r.into()) + } + } + } + + /// Places a cryptographically-secure pseudo-random number nonnegative + /// number less than `self` in `rnd`. + pub fn rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_rand_range(self.0, rnd.0)).map(|_| ()) + } + } + + /// The cryptographically weak counterpart to `rand_in_range`. + pub fn pseudo_rand_in_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_pseudo_rand_range(self.0, rnd.0)).map(|_| ()) + } + } + + /// Sets bit `n`. Equivalent to `self |= (1 << n)`. + /// + /// When setting a bit outside of `self`, it is expanded. + pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_set_bit(self.0, n.into())).map(|_| ()) + } + } + + /// Clears bit `n`, setting it to 0. Equivalent to `self &= ~(1 << n)`. + /// + /// When clearing a bit outside of `self`, an error is returned. + pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_clear_bit(self.0, n.into())).map(|_| ()) + } + } + + /// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise. + pub fn is_bit_set(&self, n: i32) -> bool { + unsafe { + ffi::BN_is_bit_set(self.0, n.into()) == 1 + } + } + + /// Truncates `self` to the lowest `n` bits. + /// + /// An error occurs if `self` is already shorter than `n` bits. + pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mask_bits(self.0, n.into())).map(|_| ()) + } + } + + /// Places `self << 1` in `r`. + pub fn lshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_lshift1(r.0, self.0)).map(|_| ()) + } + } + + /// Places `self >> 1` in `r`. + pub fn rshift1(&self, r: &mut BigNumRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_rshift1(r.0, self.0)).map(|_| ()) + } + } + + pub fn checked_add(&self, a: &BigNumRef) -> Result { + unsafe { + with_bn!(r, { + ffi::BN_add(r.as_ptr(), self.as_ptr(), a.as_ptr()) == 1 + }) + } + } + + pub fn checked_sub(&self, a: &BigNumRef) -> Result { + unsafe { + with_bn!(r, { + ffi::BN_sub(r.as_ptr(), self.as_ptr(), a.as_ptr()) == 1 + }) + } + } + + pub fn checked_mul(&self, a: &BigNumRef) -> Result { + unsafe { + with_bn_in_ctx!(r, ctx, { + ffi::BN_mul(r.as_ptr(), self.as_ptr(), a.as_ptr(), ctx) == 1 + }) + } + } + + pub fn checked_div(&self, a: &BigNumRef) -> Result { + unsafe { + with_bn_in_ctx!(r, ctx, { + ffi::BN_div(r.as_ptr(), ptr::null_mut(), self.as_ptr(), a.as_ptr(), ctx) == 1 + }) + } + } + + pub fn checked_mod(&self, a: &BigNumRef) -> Result { + unsafe { + with_bn_in_ctx!(r, ctx, { + ffi::BN_div(ptr::null_mut(), r.as_ptr(), self.as_ptr(), a.as_ptr(), ctx) == 1 + }) + } + } + + pub fn checked_shl(&self, a: &i32) -> Result { + unsafe { + with_bn!(r, { + ffi::BN_lshift(r.as_ptr(), self.as_ptr(), *a as c_int) == 1 + }) + } + } + + pub fn checked_shr(&self, a: &i32) -> Result { + unsafe { + with_bn!(r, { + ffi::BN_rshift(r.as_ptr(), self.as_ptr(), *a as c_int) == 1 + }) + } + } + + pub fn to_owned(&self) -> Result { + unsafe { + let r = try_ssl_null!(ffi::BN_dup(self.as_ptr())); + Ok(BigNum::from_ptr(r)) + } + } + + /// Inverts the sign of `self`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let mut s = BigNum::new_from(8).unwrap(); + /// + /// s.negate(); + /// assert_eq!(s, -BigNum::new_from(8).unwrap()); + /// s.negate(); + /// assert_eq!(s, BigNum::new_from(8).unwrap()); + /// ``` + pub fn negate(&mut self) { + unsafe { ffi::BN_set_negative(self.as_ptr(), !self.is_negative() as c_int) } + } + + /// Compare the absolute values of `self` and `oth`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// # use std::cmp::Ordering; + /// let s = -BigNum::new_from(8).unwrap(); + /// let o = BigNum::new_from(8).unwrap(); + /// + /// assert_eq!(s.abs_cmp(&o), Ordering::Equal); + /// ``` + pub fn abs_cmp(&self, oth: &BigNumRef) -> Ordering { + unsafe { + let res = ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()) as i32; + if res < 0 { + Ordering::Less + } else if res > 0 { + Ordering::Greater + } else { + Ordering::Equal + } + } + } + + pub fn is_negative(&self) -> bool { + self._is_negative() + } + + #[cfg(ossl10x)] + fn _is_negative(&self) -> bool { + unsafe { (*self.as_ptr()).neg == 1 } + } + + #[cfg(ossl110)] + fn _is_negative(&self) -> bool { + unsafe { ffi::BN_is_negative(self.as_ptr()) == 1 } + } + + /// Returns the number of significant bits in `self`. + pub fn num_bits(&self) -> i32 { + unsafe { ffi::BN_num_bits(self.as_ptr()) as i32 } + } + + /// Returns the size of `self` in bytes. + pub fn num_bytes(&self) -> i32 { + (self.num_bits() + 7) / 8 + } + + pub fn as_ptr(&self) -> *mut ffi::BIGNUM { + self.0 + } + + /// Returns a big-endian byte vector representation of the absolute value of `self`. + /// + /// `self` can be recreated by using `new_from_slice`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::new_from(4543).unwrap(); + /// let r = BigNum::new_from(4543).unwrap(); + /// + /// let s_vec = s.to_vec(); + /// assert_eq!(BigNum::new_from_slice(&s_vec).unwrap(), r); + /// ``` + pub fn to_vec(&self) -> Vec { + let size = self.num_bytes() as usize; + let mut v = Vec::with_capacity(size); + unsafe { + ffi::BN_bn2bin(self.as_ptr(), v.as_mut_ptr()); + v.set_len(size); + } + v + } + + /// Returns a decimal string representation of `self`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::new_from(12345).unwrap(); + /// + /// assert_eq!(s.to_dec_str(), "-12345"); + /// ``` + pub fn to_dec_str(&self) -> String { + unsafe { + let buf = ffi::BN_bn2dec(self.as_ptr()); + assert!(!buf.is_null()); + let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) + .unwrap(); + CRYPTO_free!(buf as *mut c_void); + str + } + } + + /// Returns a hexadecimal string representation of `self`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::new_from(0x99ff).unwrap(); + /// + /// assert_eq!(s.to_hex_str(), "-99FF"); + /// ``` + pub fn to_hex_str(&self) -> String { + unsafe { + let buf = ffi::BN_bn2hex(self.as_ptr()); + assert!(!buf.is_null()); + let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) + .unwrap(); + CRYPTO_free!(buf as *mut c_void); + str + } + } +} + +/// An owned, signed, arbitrary-precision integer. +/// +/// `BigNum` provides wrappers around OpenSSL's checked arithmetic functions. +/// Additionally, it implements the standard operators (`std::ops`), which +/// perform unchecked arithmetic, unwrapping the returned `Result` of the +/// checked operations. +pub struct BigNum(BigNumRef<'static>); + +impl BigNum { + /// Creates a new `BigNum` with the value 0. + pub fn new() -> Result { + unsafe { + ffi::init(); + let v = try_ssl_null!(ffi::BN_new()); + Ok(BigNum::from_ptr(v)) + } + } + + /// Creates a new `BigNum` with the given value. + pub fn new_from(n: u32) -> Result { + BigNum::new().and_then(|v| unsafe { + try_ssl!(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)); + Ok(v) + }) + } + + /// Creates a `BigNum` from a decimal string. + pub fn from_dec_str(s: &str) -> Result { + BigNum::new().and_then(|mut v| unsafe { + let c_str = CString::new(s.as_bytes()).unwrap(); + try_ssl!(ffi::BN_dec2bn(&mut (v.0).0, c_str.as_ptr() as *const _)); + Ok(v) + }) + } + + /// Creates a `BigNum` from a hexadecimal string. + pub fn from_hex_str(s: &str) -> Result { + BigNum::new().and_then(|mut v| unsafe { + let c_str = CString::new(s.as_bytes()).unwrap(); + try_ssl!(ffi::BN_hex2bn(&mut (v.0).0, c_str.as_ptr() as *const _)); + Ok(v) + }) + } + + pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNum { + BigNum(BigNumRef::from_ptr(handle)) + } + + /// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let bignum = BigNum::new_from_slice(&[0x12, 0x00, 0x34]).unwrap(); + /// + /// assert_eq!(bignum, BigNum::new_from(0x120034).unwrap()); + /// ``` + pub fn new_from_slice(n: &[u8]) -> Result { + BigNum::new().and_then(|v| unsafe { + try_ssl_null!(ffi::BN_bin2bn(n.as_ptr(), n.len() as c_int, v.as_ptr())); + Ok(v) + }) + } + /// Generates a prime number. + /// + /// # Parameters + /// + /// * `bits`: The length of the prime in bits (lower bound). + /// * `safe`: If true, returns a "safe" prime `p` so that `(p-1)/2` is also prime. + /// * `add`/`rem`: If `add` is set to `Some(add)`, `p % add == rem` will hold, where `p` is the + /// generated prime and `rem` is `1` if not specified (`None`). + pub fn checked_generate_prime(bits: i32, + safe: bool, + add: Option<&BigNum>, + rem: Option<&BigNum>) + -> Result { + unsafe { + with_bn_in_ctx!(r, ctx, { + let add_arg = add.map(|a| a.as_ptr()).unwrap_or(ptr::null_mut()); + let rem_arg = rem.map(|r| r.as_ptr()).unwrap_or(ptr::null_mut()); + + ffi::BN_generate_prime_ex(r.as_ptr(), + bits as c_int, + safe as c_int, + add_arg, + rem_arg, + ptr::null_mut()) == 1 + }) + } + } + + /// Generates a cryptographically strong pseudo-random `BigNum`. + /// + /// # Parameters + /// + /// * `bits`: Length of the number in bits. + /// * `prop`: The desired properties of the number. + /// * `odd`: If `true`, the generated number will be odd. + pub fn checked_new_random(bits: i32, prop: RNGProperty, odd: bool) -> Result { + unsafe { + with_bn_in_ctx!(r, ctx, { + ffi::BN_rand(r.as_ptr(), bits as c_int, prop as c_int, odd as c_int) == 1 + }) + } + } + + /// The cryptographically weak counterpart to `checked_new_random`. + pub fn checked_new_pseudo_random(bits: i32, + prop: RNGProperty, + odd: bool) + -> Result { + unsafe { + with_bn_in_ctx!(r, ctx, { + ffi::BN_pseudo_rand(r.as_ptr(), bits as c_int, prop as c_int, odd as c_int) == 1 + }) + } + } +} + +impl Drop for BigNum { + fn drop(&mut self) { + unsafe { ffi::BN_clear_free(self.as_ptr()); } + } +} + +impl Deref for BigNum { + type Target = BigNumRef<'static>; + + fn deref(&self) -> &BigNumRef<'static> { + &self.0 + } +} + +impl DerefMut for BigNum { + fn deref_mut(&mut self) -> &mut BigNumRef<'static> { + &mut self.0 + } +} + +impl AsRef> for BigNum { + fn as_ref(&self) -> &BigNumRef<'static> { + self.deref() + } +} + +impl<'a> fmt::Debug for BigNumRef<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.to_dec_str()) + } +} + +impl fmt::Debug for BigNum { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.to_dec_str()) + } +} + +impl<'a> fmt::Display for BigNumRef<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.to_dec_str()) + } +} + +impl fmt::Display for BigNum { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.to_dec_str()) + } +} + +impl<'a, 'b> PartialEq> for BigNumRef<'a> { + fn eq(&self, oth: &BigNumRef) -> bool { + unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()) == 0 } + } +} + +impl<'a> PartialEq for BigNumRef<'a> { + fn eq(&self, oth: &BigNum) -> bool { + self.eq(oth.deref()) + } +} + +impl<'a> Eq for BigNumRef<'a> {} + +impl PartialEq for BigNum { + fn eq(&self, oth: &BigNum) -> bool { + self.deref().eq(oth) + } +} + +impl<'a> PartialEq> for BigNum { + fn eq(&self, oth: &BigNumRef) -> bool { + self.deref().eq(oth) + } +} + +impl Eq for BigNum {} + +impl<'a, 'b> PartialOrd> for BigNumRef<'a> { + fn partial_cmp(&self, oth: &BigNumRef) -> Option { + Some(self.cmp(oth)) + } +} + +impl<'a> PartialOrd for BigNumRef<'a> { + fn partial_cmp(&self, oth: &BigNum) -> Option { + Some(self.cmp(oth.deref())) + } +} + +impl<'a> Ord for BigNumRef<'a> { + fn cmp(&self, oth: &BigNumRef) -> Ordering { + unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } + } +} + +impl PartialOrd for BigNum { + fn partial_cmp(&self, oth: &BigNum) -> Option { + self.deref().partial_cmp(oth.deref()) + } +} + +impl<'a> PartialOrd> for BigNum { + fn partial_cmp(&self, oth: &BigNumRef) -> Option { + self.deref().partial_cmp(oth) + } +} + +impl Ord for BigNum { + fn cmp(&self, oth: &BigNum) -> Ordering { + self.deref().cmp(oth.deref()) + } +} + +impl<'a, 'b> Add<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn add(self, oth: &BigNumRef) -> BigNum { + self.checked_add(oth).unwrap() + } +} + +impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn sub(self, oth: &BigNumRef) -> BigNum { + self.checked_sub(oth).unwrap() + } +} + +impl<'a, 'b> Sub<&'b BigNum> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn sub(self, oth: &BigNum) -> BigNum { + self.checked_sub(oth).unwrap() + } +} + +impl<'a, 'b> Sub<&'b BigNum> for &'a BigNum { + type Output = BigNum; + + fn sub(self, oth: &BigNum) -> BigNum { + self.checked_sub(oth).unwrap() + } +} + +impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNum { + type Output = BigNum; + + fn sub(self, oth: &BigNumRef) -> BigNum { + self.checked_sub(oth).unwrap() + } +} + +impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn mul(self, oth: &BigNumRef) -> BigNum { + self.checked_mul(oth).unwrap() + } +} + +impl<'a, 'b> Mul<&'b BigNum> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn mul(self, oth: &BigNum) -> BigNum { + self.checked_mul(oth).unwrap() + } +} + +impl<'a, 'b> Mul<&'b BigNum> for &'a BigNum { + type Output = BigNum; + + fn mul(self, oth: &BigNum) -> BigNum { + self.checked_mul(oth).unwrap() + } +} + +impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNum { + type Output = BigNum; + + fn mul(self, oth: &BigNumRef) -> BigNum { + self.checked_mul(oth).unwrap() + } +} + +impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn div(self, oth: &'b BigNumRef<'b>) -> BigNum { + self.checked_div(oth).unwrap() + } +} + +impl<'a, 'b> Div<&'b BigNum> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn div(self, oth: &'b BigNum) -> BigNum { + self.checked_div(oth).unwrap() + } +} + +impl<'a, 'b> Div<&'b BigNum> for &'a BigNum { + type Output = BigNum; + + fn div(self, oth: &'b BigNum) -> BigNum { + self.checked_div(oth).unwrap() + } +} + +impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNum { + type Output = BigNum; + + fn div(self, oth: &'b BigNumRef<'b>) -> BigNum { + self.checked_div(oth).unwrap() + } +} + +impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn rem(self, oth: &'b BigNumRef<'b>) -> BigNum { + self.checked_mod(oth).unwrap() + } +} + +impl<'a, 'b> Rem<&'b BigNum> for &'a BigNumRef<'a> { + type Output = BigNum; + + fn rem(self, oth: &'b BigNum) -> BigNum { + self.checked_mod(oth).unwrap() + } +} + +impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNum { + type Output = BigNum; + + fn rem(self, oth: &'b BigNumRef<'b>) -> BigNum { + self.checked_mod(oth).unwrap() + } +} + +impl<'a, 'b> Rem<&'b BigNum> for &'a BigNum { + type Output = BigNum; + + fn rem(self, oth: &'b BigNum) -> BigNum { + self.checked_mod(oth).unwrap() + } +} + +impl<'a> Shl for &'a BigNumRef<'a> { + type Output = BigNum; + + fn shl(self, n: i32) -> BigNum { + self.checked_shl(&n).unwrap() + } +} + +impl<'a> Shl for &'a BigNum { + type Output = BigNum; + + fn shl(self, n: i32) -> BigNum { + self.checked_shl(&n).unwrap() + } +} + +impl<'a> Shr for &'a BigNumRef<'a> { + type Output = BigNum; + + fn shr(self, n: i32) -> BigNum { + self.checked_shr(&n).unwrap() + } +} + +impl<'a> Shr for &'a BigNum { + type Output = BigNum; + + fn shr(self, n: i32) -> BigNum { + self.checked_shr(&n).unwrap() + } +} + +impl<'a> Neg for &'a BigNumRef<'a> { + type Output = BigNum; + + fn neg(self) -> BigNum { + let mut n = self.to_owned().unwrap(); + n.negate(); + n + } +} + +impl<'a> Neg for &'a BigNum { + type Output = BigNum; + + fn neg(self) -> BigNum { + let mut n = self.deref().to_owned().unwrap(); + n.negate(); + n + } +} + +impl Neg for BigNum { + type Output = BigNum; + + fn neg(mut self) -> BigNum { + self.negate(); + self + } +} + +#[cfg(test)] +mod tests { + use bn::{BnCtx, BigNum}; + + #[test] + fn test_to_from_slice() { + let v0 = BigNum::new_from(10203004).unwrap(); + let vec = v0.to_vec(); + let v1 = BigNum::new_from_slice(&vec).unwrap(); + + assert!(v0 == v1); + } + + #[test] + fn test_negation() { + let a = BigNum::new_from(909829283).unwrap(); + + assert!(!a.is_negative()); + assert!((-a).is_negative()); + } + + + #[test] + fn test_prime_numbers() { + let a = BigNum::new_from(19029017).unwrap(); + let p = BigNum::checked_generate_prime(128, true, None, Some(&a)).unwrap(); + + let mut ctx = BnCtx::new().unwrap(); + assert!(ctx.is_prime(&p, 100).unwrap()); + assert!(ctx.is_prime_fasttest(&p, 100, true).unwrap()); + } +} diff --git a/openssl/src/bn/mod.rs b/openssl/src/bn/mod.rs deleted file mode 100644 index 7d1f5458..00000000 --- a/openssl/src/bn/mod.rs +++ /dev/null @@ -1,1037 +0,0 @@ -use libc::{c_int, c_void}; -use std::ffi::{CStr, CString}; -use std::cmp::Ordering; -use std::{fmt, ptr}; -use std::marker::PhantomData; -use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref, DerefMut}; - -use ffi; -use error::ErrorStack; - -/// Specifies the desired properties of a randomly generated `BigNum`. -#[derive(Copy, Clone)] -#[repr(C)] -pub enum RNGProperty { - /// The most significant bit of the number is allowed to be 0. - MsbMaybeZero = -1, - /// The MSB should be set to 1. - MsbOne = 0, - /// The two most significant bits of the number will be set to 1, so that the product of two - /// such random numbers will always have `2 * bits` length. - TwoMsbOne = 1, -} - -macro_rules! with_ctx( - ($name:ident, $action:block) => ({ - let $name = ffi::BN_CTX_new(); - if ($name).is_null() { - Err(ErrorStack::get()) - } else { - let r = $action; - ffi::BN_CTX_free($name); - r - } - }); -); - -macro_rules! with_bn( - ($name:ident, $action:block) => ({ - let tmp = BigNum::new(); - match tmp { - Ok($name) => { - if $action { - Ok($name) - } else { - Err(ErrorStack::get()) - } - }, - Err(err) => Err(err), - } - }); -); - -macro_rules! with_bn_in_ctx( - ($name:ident, $ctx_name:ident, $action:block) => ({ - let tmp = BigNum::new(); - match tmp { - Ok($name) => { - let $ctx_name = ffi::BN_CTX_new(); - if ($ctx_name).is_null() { - Err(ErrorStack::get()) - } else { - let r = - if $action { - Ok($name) - } else { - Err(ErrorStack::get()) - }; - ffi::BN_CTX_free($ctx_name); - r - } - }, - Err(err) => Err(err), - } - }); -); - -/// A borrowed, signed, arbitrary-precision integer. -#[derive(Copy, Clone)] -pub struct BigNumRef<'a>(*mut ffi::BIGNUM, PhantomData<&'a ()>); - - -impl<'a> BigNumRef<'a> { - pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNumRef<'a> { - BigNumRef(handle, PhantomData) - } - - /// Returns the square of `self`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let ref n = BigNum::new_from(10).unwrap(); - /// let squared = BigNum::new_from(100).unwrap(); - /// - /// assert_eq!(n.checked_sqr().unwrap(), squared); - /// assert_eq!(n * n, squared); - /// ``` - pub fn checked_sqr(&self) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_sqr(r.as_ptr(), self.as_ptr(), ctx) == 1 - }) - } - } - - /// Returns the unsigned remainder of the division `self / n`. - pub fn checked_nnmod(&self, n: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_nnmod(r.as_ptr(), self.as_ptr(), n.as_ptr(), ctx) == 1 - }) - } - } - - /// Equivalent to `(self + a) mod n`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let ref s = BigNum::new_from(10).unwrap(); - /// let ref a = BigNum::new_from(20).unwrap(); - /// let ref n = BigNum::new_from(29).unwrap(); - /// let result = BigNum::new_from(1).unwrap(); - /// - /// assert_eq!(s.checked_mod_add(a, n).unwrap(), result); - /// ``` - pub fn checked_mod_add(&self, a: &BigNumRef, n: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_add(r.as_ptr(), self.as_ptr(), a.as_ptr(), n.as_ptr(), ctx) == 1 - }) - } - } - - /// Equivalent to `(self - a) mod n`. - pub fn checked_mod_sub(&self, a: &BigNumRef, n: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_sub(r.as_ptr(), self.as_ptr(), a.as_ptr(), n.as_ptr(), ctx) == 1 - }) - } - } - - /// Equivalent to `(self * a) mod n`. - pub fn checked_mod_mul(&self, a: &BigNumRef, n: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_mul(r.as_ptr(), self.as_ptr(), a.as_ptr(), n.as_ptr(), ctx) == 1 - }) - } - } - - /// Equivalent to `self² mod n`. - pub fn checked_mod_sqr(&self, n: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_sqr(r.as_ptr(), self.as_ptr(), n.as_ptr(), ctx) == 1 - }) - } - } - - /// Raises `self` to the `p`th power. - pub fn checked_exp(&self, p: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_exp(r.as_ptr(), self.as_ptr(), p.as_ptr(), ctx) == 1 - }) - } - } - - /// Equivalent to `self.checked_exp(p) mod n`. - pub fn checked_mod_exp(&self, p: &BigNumRef, n: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mod_exp(r.as_ptr(), self.as_ptr(), p.as_ptr(), n.as_ptr(), ctx) == 1 - }) - } - } - - /// Calculates the modular multiplicative inverse of `self` modulo `n`, that is, an integer `r` - /// such that `(self * r) % n == 1`. - pub fn checked_mod_inv(&self, n: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - !ffi::BN_mod_inverse(r.as_ptr(), self.as_ptr(), n.as_ptr(), ctx).is_null() - }) - } - } - - /// Add a `u32` to `self`. This is more efficient than adding a - /// `BigNum`. - pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { - if ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } - } - } - - pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { - if ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } - } - } - - pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { - if ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } - } - } - - pub fn div_word(&mut self, w: u32) -> Result { - unsafe { - let result = ffi::BN_div_word(self.as_ptr(), w as ffi::BN_ULONG); - if result != !0 { - Ok(result.into()) - } else { - Err(ErrorStack::get()) - } - } - } - - pub fn mod_word(&self, w: u32) -> Result { - unsafe { - let result = ffi::BN_mod_word(self.as_ptr(), w as ffi::BN_ULONG); - if result != !0 { - Ok(result as u64) - } else { - Err(ErrorStack::get()) - } - } - } - - /// Computes the greatest common denominator of `self` and `a`. - pub fn checked_gcd(&self, a: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_gcd(r.as_ptr(), self.as_ptr(), a.as_ptr(), ctx) == 1 - }) - } - } - - /// Checks whether `self` is prime. - /// - /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. - /// - /// # Return Value - /// - /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime(&self, checks: i32) -> Result { - unsafe { - with_ctx!(ctx, { - Ok(ffi::BN_is_prime_ex(self.as_ptr(), - checks as c_int, - ctx, - ptr::null_mut()) == 1) - }) - } - } - - /// Checks whether `self` is prime with optional trial division. - /// - /// If `do_trial_division` is `true`, first performs trial division by a number of small primes. - /// Then, like `is_prime`, performs a Miller-Rabin probabilistic primality test with `checks` - /// iterations. - /// - /// # Return Value - /// - /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime_fast(&self, checks: i32, do_trial_division: bool) -> Result { - unsafe { - with_ctx!(ctx, { - Ok(ffi::BN_is_prime_fasttest_ex(self.as_ptr(), - checks as c_int, - ctx, - do_trial_division as c_int, - ptr::null_mut()) == 1) - }) - } - } - - /// Generates a cryptographically strong pseudo-random `BigNum` `r` in the range - /// `0 <= r < self`. - pub fn checked_rand_in_range(&self) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_rand_range(r.as_ptr(), self.as_ptr()) == 1 - }) - } - } - - /// The cryptographically weak counterpart to `checked_rand_in_range`. - pub fn checked_pseudo_rand_in_range(&self) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_pseudo_rand_range(r.as_ptr(), self.as_ptr()) == 1 - }) - } - } - - /// Sets bit `n`. Equivalent to `self |= (1 << n)`. - /// - /// When setting a bit outside of `self`, it is expanded. - pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { - if ffi::BN_set_bit(self.as_ptr(), n as c_int) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } - } - } - - /// Clears bit `n`, setting it to 0. Equivalent to `self &= ~(1 << n)`. - /// - /// When clearing a bit outside of `self`, an error is returned. - pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { - if ffi::BN_clear_bit(self.as_ptr(), n as c_int) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } - } - } - - /// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise. - pub fn is_bit_set(&self, n: i32) -> bool { - unsafe { ffi::BN_is_bit_set(self.as_ptr(), n as c_int) == 1 } - } - - /// Truncates `self` to the lowest `n` bits. - /// - /// An error occurs if `self` is already shorter than `n` bits. - pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { - if ffi::BN_mask_bits(self.as_ptr(), n as c_int) == 1 { - Ok(()) - } else { - Err(ErrorStack::get()) - } - } - } - - /// Returns `self`, shifted left by 1 bit. `self` may be negative. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let ref s = BigNum::new_from(0b0100).unwrap(); - /// let result = BigNum::new_from(0b1000).unwrap(); - /// - /// assert_eq!(s.checked_shl1().unwrap(), result); - /// ``` - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let ref s = -BigNum::new_from(8).unwrap(); - /// let result = -BigNum::new_from(16).unwrap(); - /// - /// // (-8) << 1 == -16 - /// assert_eq!(s.checked_shl1().unwrap(), result); - /// ``` - pub fn checked_shl1(&self) -> Result { - unsafe { - with_bn!(r, { - ffi::BN_lshift1(r.as_ptr(), self.as_ptr()) == 1 - }) - } - } - - /// Returns `self`, shifted right by 1 bit. `self` may be negative. - pub fn checked_shr1(&self) -> Result { - unsafe { - with_bn!(r, { - ffi::BN_rshift1(r.as_ptr(), self.as_ptr()) == 1 - }) - } - } - - pub fn checked_add(&self, a: &BigNumRef) -> Result { - unsafe { - with_bn!(r, { - ffi::BN_add(r.as_ptr(), self.as_ptr(), a.as_ptr()) == 1 - }) - } - } - - pub fn checked_sub(&self, a: &BigNumRef) -> Result { - unsafe { - with_bn!(r, { - ffi::BN_sub(r.as_ptr(), self.as_ptr(), a.as_ptr()) == 1 - }) - } - } - - pub fn checked_mul(&self, a: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_mul(r.as_ptr(), self.as_ptr(), a.as_ptr(), ctx) == 1 - }) - } - } - - pub fn checked_div(&self, a: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_div(r.as_ptr(), ptr::null_mut(), self.as_ptr(), a.as_ptr(), ctx) == 1 - }) - } - } - - pub fn checked_mod(&self, a: &BigNumRef) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_div(ptr::null_mut(), r.as_ptr(), self.as_ptr(), a.as_ptr(), ctx) == 1 - }) - } - } - - pub fn checked_shl(&self, a: &i32) -> Result { - unsafe { - with_bn!(r, { - ffi::BN_lshift(r.as_ptr(), self.as_ptr(), *a as c_int) == 1 - }) - } - } - - pub fn checked_shr(&self, a: &i32) -> Result { - unsafe { - with_bn!(r, { - ffi::BN_rshift(r.as_ptr(), self.as_ptr(), *a as c_int) == 1 - }) - } - } - - pub fn to_owned(&self) -> Result { - unsafe { - let r = try_ssl_null!(ffi::BN_dup(self.as_ptr())); - Ok(BigNum::from_ptr(r)) - } - } - - /// Inverts the sign of `self`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let mut s = BigNum::new_from(8).unwrap(); - /// - /// s.negate(); - /// assert_eq!(s, -BigNum::new_from(8).unwrap()); - /// s.negate(); - /// assert_eq!(s, BigNum::new_from(8).unwrap()); - /// ``` - pub fn negate(&mut self) { - unsafe { ffi::BN_set_negative(self.as_ptr(), !self.is_negative() as c_int) } - } - - /// Compare the absolute values of `self` and `oth`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// # use std::cmp::Ordering; - /// let s = -BigNum::new_from(8).unwrap(); - /// let o = BigNum::new_from(8).unwrap(); - /// - /// assert_eq!(s.abs_cmp(&o), Ordering::Equal); - /// ``` - pub fn abs_cmp(&self, oth: &BigNumRef) -> Ordering { - unsafe { - let res = ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()) as i32; - if res < 0 { - Ordering::Less - } else if res > 0 { - Ordering::Greater - } else { - Ordering::Equal - } - } - } - - pub fn is_negative(&self) -> bool { - self._is_negative() - } - - #[cfg(ossl10x)] - fn _is_negative(&self) -> bool { - unsafe { (*self.as_ptr()).neg == 1 } - } - - #[cfg(ossl110)] - fn _is_negative(&self) -> bool { - unsafe { ffi::BN_is_negative(self.as_ptr()) == 1 } - } - - /// Returns the number of significant bits in `self`. - pub fn num_bits(&self) -> i32 { - unsafe { ffi::BN_num_bits(self.as_ptr()) as i32 } - } - - /// Returns the size of `self` in bytes. - pub fn num_bytes(&self) -> i32 { - (self.num_bits() + 7) / 8 - } - - pub fn as_ptr(&self) -> *mut ffi::BIGNUM { - self.0 - } - - /// Returns a big-endian byte vector representation of the absolute value of `self`. - /// - /// `self` can be recreated by using `new_from_slice`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let s = -BigNum::new_from(4543).unwrap(); - /// let r = BigNum::new_from(4543).unwrap(); - /// - /// let s_vec = s.to_vec(); - /// assert_eq!(BigNum::new_from_slice(&s_vec).unwrap(), r); - /// ``` - pub fn to_vec(&self) -> Vec { - let size = self.num_bytes() as usize; - let mut v = Vec::with_capacity(size); - unsafe { - ffi::BN_bn2bin(self.as_ptr(), v.as_mut_ptr()); - v.set_len(size); - } - v - } - - /// Returns a decimal string representation of `self`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let s = -BigNum::new_from(12345).unwrap(); - /// - /// assert_eq!(s.to_dec_str(), "-12345"); - /// ``` - pub fn to_dec_str(&self) -> String { - unsafe { - let buf = ffi::BN_bn2dec(self.as_ptr()); - assert!(!buf.is_null()); - let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) - .unwrap(); - CRYPTO_free!(buf as *mut c_void); - str - } - } - - /// Returns a hexadecimal string representation of `self`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let s = -BigNum::new_from(0x99ff).unwrap(); - /// - /// assert_eq!(s.to_hex_str(), "-99FF"); - /// ``` - pub fn to_hex_str(&self) -> String { - unsafe { - let buf = ffi::BN_bn2hex(self.as_ptr()); - assert!(!buf.is_null()); - let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()) - .unwrap(); - CRYPTO_free!(buf as *mut c_void); - str - } - } -} - -/// An owned, signed, arbitrary-precision integer. -/// -/// `BigNum` provides wrappers around OpenSSL's checked arithmetic functions. -/// Additionally, it implements the standard operators (`std::ops`), which -/// perform unchecked arithmetic, unwrapping the returned `Result` of the -/// checked operations. -pub struct BigNum(BigNumRef<'static>); - -impl BigNum { - /// Creates a new `BigNum` with the value 0. - pub fn new() -> Result { - unsafe { - ffi::init(); - let v = try_ssl_null!(ffi::BN_new()); - Ok(BigNum::from_ptr(v)) - } - } - - /// Creates a new `BigNum` with the given value. - pub fn new_from(n: u32) -> Result { - BigNum::new().and_then(|v| unsafe { - try_ssl!(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)); - Ok(v) - }) - } - - /// Creates a `BigNum` from a decimal string. - pub fn from_dec_str(s: &str) -> Result { - BigNum::new().and_then(|mut v| unsafe { - let c_str = CString::new(s.as_bytes()).unwrap(); - try_ssl!(ffi::BN_dec2bn(&mut (v.0).0, c_str.as_ptr() as *const _)); - Ok(v) - }) - } - - /// Creates a `BigNum` from a hexadecimal string. - pub fn from_hex_str(s: &str) -> Result { - BigNum::new().and_then(|mut v| unsafe { - let c_str = CString::new(s.as_bytes()).unwrap(); - try_ssl!(ffi::BN_hex2bn(&mut (v.0).0, c_str.as_ptr() as *const _)); - Ok(v) - }) - } - - pub unsafe fn from_ptr(handle: *mut ffi::BIGNUM) -> BigNum { - BigNum(BigNumRef::from_ptr(handle)) - } - - /// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let bignum = BigNum::new_from_slice(&[0x12, 0x00, 0x34]).unwrap(); - /// - /// assert_eq!(bignum, BigNum::new_from(0x120034).unwrap()); - /// ``` - pub fn new_from_slice(n: &[u8]) -> Result { - BigNum::new().and_then(|v| unsafe { - try_ssl_null!(ffi::BN_bin2bn(n.as_ptr(), n.len() as c_int, v.as_ptr())); - Ok(v) - }) - } - /// Generates a prime number. - /// - /// # Parameters - /// - /// * `bits`: The length of the prime in bits (lower bound). - /// * `safe`: If true, returns a "safe" prime `p` so that `(p-1)/2` is also prime. - /// * `add`/`rem`: If `add` is set to `Some(add)`, `p % add == rem` will hold, where `p` is the - /// generated prime and `rem` is `1` if not specified (`None`). - pub fn checked_generate_prime(bits: i32, - safe: bool, - add: Option<&BigNum>, - rem: Option<&BigNum>) - -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - let add_arg = add.map(|a| a.as_ptr()).unwrap_or(ptr::null_mut()); - let rem_arg = rem.map(|r| r.as_ptr()).unwrap_or(ptr::null_mut()); - - ffi::BN_generate_prime_ex(r.as_ptr(), - bits as c_int, - safe as c_int, - add_arg, - rem_arg, - ptr::null_mut()) == 1 - }) - } - } - - /// Generates a cryptographically strong pseudo-random `BigNum`. - /// - /// # Parameters - /// - /// * `bits`: Length of the number in bits. - /// * `prop`: The desired properties of the number. - /// * `odd`: If `true`, the generated number will be odd. - pub fn checked_new_random(bits: i32, prop: RNGProperty, odd: bool) -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_rand(r.as_ptr(), bits as c_int, prop as c_int, odd as c_int) == 1 - }) - } - } - - /// The cryptographically weak counterpart to `checked_new_random`. - pub fn checked_new_pseudo_random(bits: i32, - prop: RNGProperty, - odd: bool) - -> Result { - unsafe { - with_bn_in_ctx!(r, ctx, { - ffi::BN_pseudo_rand(r.as_ptr(), bits as c_int, prop as c_int, odd as c_int) == 1 - }) - } - } -} - -impl Drop for BigNum { - fn drop(&mut self) { - unsafe { ffi::BN_clear_free(self.as_ptr()); } - } -} - -impl Deref for BigNum { - type Target = BigNumRef<'static>; - - fn deref(&self) -> &BigNumRef<'static> { - &self.0 - } -} - -impl DerefMut for BigNum { - fn deref_mut(&mut self) -> &mut BigNumRef<'static> { - &mut self.0 - } -} - -impl AsRef> for BigNum { - fn as_ref(&self) -> &BigNumRef<'static> { - self.deref() - } -} - -impl<'a> fmt::Debug for BigNumRef<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_dec_str()) - } -} - -impl fmt::Debug for BigNum { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_dec_str()) - } -} - -impl<'a> fmt::Display for BigNumRef<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_dec_str()) - } -} - -impl fmt::Display for BigNum { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_dec_str()) - } -} - -impl<'a, 'b> PartialEq> for BigNumRef<'a> { - fn eq(&self, oth: &BigNumRef) -> bool { - unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()) == 0 } - } -} - -impl<'a> PartialEq for BigNumRef<'a> { - fn eq(&self, oth: &BigNum) -> bool { - self.eq(oth.deref()) - } -} - -impl<'a> Eq for BigNumRef<'a> {} - -impl PartialEq for BigNum { - fn eq(&self, oth: &BigNum) -> bool { - self.deref().eq(oth) - } -} - -impl<'a> PartialEq> for BigNum { - fn eq(&self, oth: &BigNumRef) -> bool { - self.deref().eq(oth) - } -} - -impl Eq for BigNum {} - -impl<'a, 'b> PartialOrd> for BigNumRef<'a> { - fn partial_cmp(&self, oth: &BigNumRef) -> Option { - Some(self.cmp(oth)) - } -} - -impl<'a> PartialOrd for BigNumRef<'a> { - fn partial_cmp(&self, oth: &BigNum) -> Option { - Some(self.cmp(oth.deref())) - } -} - -impl<'a> Ord for BigNumRef<'a> { - fn cmp(&self, oth: &BigNumRef) -> Ordering { - unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } - } -} - -impl PartialOrd for BigNum { - fn partial_cmp(&self, oth: &BigNum) -> Option { - self.deref().partial_cmp(oth.deref()) - } -} - -impl<'a> PartialOrd> for BigNum { - fn partial_cmp(&self, oth: &BigNumRef) -> Option { - self.deref().partial_cmp(oth) - } -} - -impl Ord for BigNum { - fn cmp(&self, oth: &BigNum) -> Ordering { - self.deref().cmp(oth.deref()) - } -} - -impl<'a, 'b> Add<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn add(self, oth: &BigNumRef) -> BigNum { - self.checked_add(oth).unwrap() - } -} - -impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn sub(self, oth: &BigNumRef) -> BigNum { - self.checked_sub(oth).unwrap() - } -} - -impl<'a, 'b> Sub<&'b BigNum> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn sub(self, oth: &BigNum) -> BigNum { - self.checked_sub(oth).unwrap() - } -} - -impl<'a, 'b> Sub<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn sub(self, oth: &BigNum) -> BigNum { - self.checked_sub(oth).unwrap() - } -} - -impl<'a, 'b> Sub<&'b BigNumRef<'b>> for &'a BigNum { - type Output = BigNum; - - fn sub(self, oth: &BigNumRef) -> BigNum { - self.checked_sub(oth).unwrap() - } -} - -impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn mul(self, oth: &BigNumRef) -> BigNum { - self.checked_mul(oth).unwrap() - } -} - -impl<'a, 'b> Mul<&'b BigNum> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn mul(self, oth: &BigNum) -> BigNum { - self.checked_mul(oth).unwrap() - } -} - -impl<'a, 'b> Mul<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn mul(self, oth: &BigNum) -> BigNum { - self.checked_mul(oth).unwrap() - } -} - -impl<'a, 'b> Mul<&'b BigNumRef<'b>> for &'a BigNum { - type Output = BigNum; - - fn mul(self, oth: &BigNumRef) -> BigNum { - self.checked_mul(oth).unwrap() - } -} - -impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn div(self, oth: &'b BigNumRef<'b>) -> BigNum { - self.checked_div(oth).unwrap() - } -} - -impl<'a, 'b> Div<&'b BigNum> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn div(self, oth: &'b BigNum) -> BigNum { - self.checked_div(oth).unwrap() - } -} - -impl<'a, 'b> Div<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn div(self, oth: &'b BigNum) -> BigNum { - self.checked_div(oth).unwrap() - } -} - -impl<'a, 'b> Div<&'b BigNumRef<'b>> for &'a BigNum { - type Output = BigNum; - - fn div(self, oth: &'b BigNumRef<'b>) -> BigNum { - self.checked_div(oth).unwrap() - } -} - -impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn rem(self, oth: &'b BigNumRef<'b>) -> BigNum { - self.checked_mod(oth).unwrap() - } -} - -impl<'a, 'b> Rem<&'b BigNum> for &'a BigNumRef<'a> { - type Output = BigNum; - - fn rem(self, oth: &'b BigNum) -> BigNum { - self.checked_mod(oth).unwrap() - } -} - -impl<'a, 'b> Rem<&'b BigNumRef<'b>> for &'a BigNum { - type Output = BigNum; - - fn rem(self, oth: &'b BigNumRef<'b>) -> BigNum { - self.checked_mod(oth).unwrap() - } -} - -impl<'a, 'b> Rem<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn rem(self, oth: &'b BigNum) -> BigNum { - self.checked_mod(oth).unwrap() - } -} - -impl<'a> Shl for &'a BigNumRef<'a> { - type Output = BigNum; - - fn shl(self, n: i32) -> BigNum { - self.checked_shl(&n).unwrap() - } -} - -impl<'a> Shl for &'a BigNum { - type Output = BigNum; - - fn shl(self, n: i32) -> BigNum { - self.checked_shl(&n).unwrap() - } -} - -impl<'a> Shr for &'a BigNumRef<'a> { - type Output = BigNum; - - fn shr(self, n: i32) -> BigNum { - self.checked_shr(&n).unwrap() - } -} - -impl<'a> Shr for &'a BigNum { - type Output = BigNum; - - fn shr(self, n: i32) -> BigNum { - self.checked_shr(&n).unwrap() - } -} - -impl<'a> Neg for &'a BigNumRef<'a> { - type Output = BigNum; - - fn neg(self) -> BigNum { - let mut n = self.to_owned().unwrap(); - n.negate(); - n - } -} - -impl<'a> Neg for &'a BigNum { - type Output = BigNum; - - fn neg(self) -> BigNum { - let mut n = self.deref().to_owned().unwrap(); - n.negate(); - n - } -} - -impl Neg for BigNum { - type Output = BigNum; - - fn neg(mut self) -> BigNum { - self.negate(); - self - } -} - -#[cfg(test)] -mod tests { - use bn::BigNum; - - #[test] - fn test_to_from_slice() { - let v0 = BigNum::new_from(10203004).unwrap(); - let vec = v0.to_vec(); - let v1 = BigNum::new_from_slice(&vec).unwrap(); - - assert!(v0 == v1); - } - - #[test] - fn test_negation() { - let a = BigNum::new_from(909829283).unwrap(); - - assert!(!a.is_negative()); - assert!((-a).is_negative()); - } - - - #[test] - fn test_prime_numbers() { - let a = BigNum::new_from(19029017).unwrap(); - let p = BigNum::checked_generate_prime(128, true, None, Some(&a)).unwrap(); - - assert!(p.is_prime(100).unwrap()); - assert!(p.is_prime_fast(100, true).unwrap()); - } -} diff --git a/openssl/src/dh.rs b/openssl/src/dh.rs new file mode 100644 index 00000000..6d0800a1 --- /dev/null +++ b/openssl/src/dh.rs @@ -0,0 +1,142 @@ +use ffi; +use error::ErrorStack; +use bio::MemBioSlice; +use std::ptr; + +use bn::BigNum; +use std::mem; + +pub struct DH(*mut ffi::DH); + +impl DH { + pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { + unsafe { + let dh = DH(try_ssl_null!(ffi::DH_new())); + try_ssl!(compat::DH_set0_pqg(dh.0, + p.as_ptr(), + q.as_ptr(), + g.as_ptr())); + mem::forget((p, g, q)); + Ok(dh) + } + } + + pub fn from_pem(buf: &[u8]) -> Result { + let mem_bio = try!(MemBioSlice::new(buf)); + let dh = unsafe { + ffi::PEM_read_bio_DHparams(mem_bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut()) + }; + try_ssl_null!(dh); + Ok(DH(dh)) + } + + #[cfg(feature = "openssl-102")] + pub fn get_1024_160() -> Result { + let dh = try_ssl_null!(unsafe { ffi::DH_get_1024_160() }); + Ok(DH(dh)) + } + + #[cfg(feature = "openssl-102")] + pub fn get_2048_224() -> Result { + let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_224() }); + Ok(DH(dh)) + } + + #[cfg(feature = "openssl-102")] + pub fn get_2048_256() -> Result { + let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_256() }); + Ok(DH(dh)) + } + + pub unsafe fn as_ptr(&self) -> *mut ffi::DH { + let DH(n) = *self; + n + } +} + +impl Drop for DH { + fn drop(&mut self) { + unsafe { + ffi::DH_free(self.as_ptr()) + } + } +} + +#[cfg(ossl110)] +mod compat { + pub use ffi::DH_set0_pqg; +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use ffi; + use libc::c_int; + + pub unsafe fn DH_set0_pqg(dh: *mut ffi::DH, + p: *mut ffi::BIGNUM, + q: *mut ffi::BIGNUM, + g: *mut ffi::BIGNUM) -> c_int { + (*dh).p = p; + (*dh).q = q; + (*dh).g = g; + 1 + } +} + +#[cfg(test)] +mod tests { + use super::DH; + use bn::BigNum; + use ssl::{SslMethod, SslContext}; + + #[test] + #[cfg(feature = "openssl-102")] + fn test_dh_rfc5114() { + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let dh1 = DH::get_1024_160().unwrap(); + ctx.set_tmp_dh(&dh1).unwrap(); + let dh2 = DH::get_2048_224().unwrap(); + ctx.set_tmp_dh(&dh2).unwrap(); + let dh3 = DH::get_2048_256().unwrap(); + ctx.set_tmp_dh(&dh3).unwrap(); + } + + #[test] + fn test_dh() { + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435\ + E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF429\ + 6D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C02\ + 2E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF1230\ + 7F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9\ + A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251C\ + CACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE\ + 621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D227\ + 6E11715F693877FAD7EF09CADB094AE91E1A1597") + .unwrap(); + let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0\ + BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773\ + BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2D\ + DF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428E\ + BC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BF\ + FE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7\ + D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92\ + B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148\ + D47954515E2327CFEF98C582664B4C0F6CC41659") + .unwrap(); + let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F\ + 5FBD3") + .unwrap(); + let dh = DH::from_params(p, g, q).unwrap(); + ctx.set_tmp_dh(&dh).unwrap(); + } + + #[test] + fn test_dh_from_pem() { + let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); + let params = include_bytes!("../test/dhparams.pem"); + let dh = DH::from_pem(params).ok().expect("Failed to load PEM"); + ctx.set_tmp_dh(&dh).unwrap(); + } +} diff --git a/openssl/src/dh/mod.rs b/openssl/src/dh/mod.rs deleted file mode 100644 index 83807f39..00000000 --- a/openssl/src/dh/mod.rs +++ /dev/null @@ -1,142 +0,0 @@ -use ffi; -use error::ErrorStack; -use bio::MemBioSlice; -use std::ptr; - -use bn::BigNum; -use std::mem; - -pub struct DH(*mut ffi::DH); - -impl DH { - pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { - unsafe { - let dh = DH(try_ssl_null!(ffi::DH_new())); - try_ssl!(compat::DH_set0_pqg(dh.0, - p.as_ptr(), - q.as_ptr(), - g.as_ptr())); - mem::forget((p, g, q)); - Ok(dh) - } - } - - pub fn from_pem(buf: &[u8]) -> Result { - let mem_bio = try!(MemBioSlice::new(buf)); - let dh = unsafe { - ffi::PEM_read_bio_DHparams(mem_bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut()) - }; - try_ssl_null!(dh); - Ok(DH(dh)) - } - - #[cfg(feature = "openssl-102")] - pub fn get_1024_160() -> Result { - let dh = try_ssl_null!(unsafe { ffi::DH_get_1024_160() }); - Ok(DH(dh)) - } - - #[cfg(feature = "openssl-102")] - pub fn get_2048_224() -> Result { - let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_224() }); - Ok(DH(dh)) - } - - #[cfg(feature = "openssl-102")] - pub fn get_2048_256() -> Result { - let dh = try_ssl_null!(unsafe { ffi::DH_get_2048_256() }); - Ok(DH(dh)) - } - - pub unsafe fn as_ptr(&self) -> *mut ffi::DH { - let DH(n) = *self; - n - } -} - -impl Drop for DH { - fn drop(&mut self) { - unsafe { - ffi::DH_free(self.as_ptr()) - } - } -} - -#[cfg(ossl110)] -mod compat { - pub use ffi::DH_set0_pqg; -} - -#[cfg(ossl10x)] -#[allow(bad_style)] -mod compat { - use ffi; - use libc::c_int; - - pub unsafe fn DH_set0_pqg(dh: *mut ffi::DH, - p: *mut ffi::BIGNUM, - q: *mut ffi::BIGNUM, - g: *mut ffi::BIGNUM) -> c_int { - (*dh).p = p; - (*dh).q = q; - (*dh).g = g; - 1 - } -} - -#[cfg(test)] -mod tests { - use super::DH; - use bn::BigNum; - use ssl::{SslMethod, SslContext}; - - #[test] - #[cfg(feature = "openssl-102")] - fn test_dh_rfc5114() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); - let dh1 = DH::get_1024_160().unwrap(); - ctx.set_tmp_dh(&dh1).unwrap(); - let dh2 = DH::get_2048_224().unwrap(); - ctx.set_tmp_dh(&dh2).unwrap(); - let dh3 = DH::get_2048_256().unwrap(); - ctx.set_tmp_dh(&dh3).unwrap(); - } - - #[test] - fn test_dh() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); - let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435\ - E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF429\ - 6D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C02\ - 2E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF1230\ - 7F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9\ - A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251C\ - CACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE\ - 621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D227\ - 6E11715F693877FAD7EF09CADB094AE91E1A1597") - .unwrap(); - let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0\ - BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773\ - BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2D\ - DF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428E\ - BC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BF\ - FE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7\ - D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92\ - B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148\ - D47954515E2327CFEF98C582664B4C0F6CC41659") - .unwrap(); - let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F\ - 5FBD3") - .unwrap(); - let dh = DH::from_params(p, g, q).unwrap(); - ctx.set_tmp_dh(&dh).unwrap(); - } - - #[test] - fn test_dh_from_pem() { - let mut ctx = SslContext::new(SslMethod::tls()).unwrap(); - let params = include_bytes!("../../test/dhparams.pem"); - let dh = DH::from_pem(params).ok().expect("Failed to load PEM"); - ctx.set_tmp_dh(&dh).unwrap(); - } -} diff --git a/openssl/src/lib.rs b/openssl/src/lib.rs index 62968742..39c9fffe 100644 --- a/openssl/src/lib.rs +++ b/openssl/src/lib.rs @@ -16,6 +16,10 @@ extern crate tempdir; #[doc(inline)] pub use ffi::init; +use libc::c_int; + +use error::ErrorStack; + mod macros; pub mod asn1; @@ -28,3 +32,27 @@ pub mod nid; pub mod ssl; pub mod version; pub mod x509; + +pub fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { + if r.is_null() { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} + +pub fn cvt(r: c_int) -> Result { + if r <= 0 { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} + +pub fn cvt_n(r: c_int) -> Result { + if r < 0 { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} -- cgit v1.2.3