This commit is contained in:
Andy Gauge 2017-10-09 12:10:04 -07:00
commit 2c7f0e7604
30 changed files with 743 additions and 296 deletions

View File

@ -78,9 +78,9 @@ openssl_101: &OPENSSL_101
libressl_250: &LIBRESSL_250
LIBRARY: libressl
VERSION: 2.5.0
libressl_261: &LIBRESSL_261
libressl_261: &LIBRESSL_262
LIBRARY: libressl
VERSION: 2.6.1
VERSION: 2.6.2
x86_64: &X86_64
TARGET: x86_64-unknown-linux-gnu
@ -139,10 +139,10 @@ jobs:
<<: *JOB
environment:
<<: [*LIBRESSL_250, *X86_64, *BASE]
x86_64-libressl-2.6.1:
x86_64-libressl-2.6.2:
<<: *JOB
environment:
<<: [*LIBRESSL_261, *X86_64, *BASE]
<<: [*LIBRESSL_262, *X86_64, *BASE]
workflows:
version: 2
tests:
@ -157,4 +157,4 @@ workflows:
- armhf-openssl-1.0.2
- armhf-openssl-1.0.1
- x86_64-libressl-2.5.0
- x86_64-libressl-2.6.1
- x86_64-libressl-2.6.2

View File

@ -316,8 +316,10 @@ fn validate_headers(include_dirs: &[PathBuf]) -> Version {
#include <openssl/opensslv.h>
#include <openssl/opensslconf.h>
#if LIBRESSL_VERSION_NUMBER >= 0x20602000
#if LIBRESSL_VERSION_NUMBER >= 0x20603000
RUST_LIBRESSL_NEW
#elif LIBRESSL_VERSION_NUMBER >= 0x20602000
RUST_LIBRESSL_262
#elif LIBRESSL_VERSION_NUMBER >= 0x20601000
RUST_LIBRESSL_261
#elif LIBRESSL_VERSION_NUMBER >= 0x20600000
@ -466,6 +468,13 @@ See rust-openssl README for more information:
println!("cargo:libressl_version=261");
println!("cargo:version=101");
Version::Libressl
} else if expanded.contains("RUST_LIBRESSL_262") {
println!("cargo:rustc-cfg=libressl");
println!("cargo:rustc-cfg=libressl262");
println!("cargo:libressl=true");
println!("cargo:libressl_version=262");
println!("cargo:version=101");
Version::Libressl
} else if expanded.contains("RUST_OPENSSL_110F") {
println!("cargo:rustc-cfg=ossl110");
println!("cargo:rustc-cfg=ossl110f");

View File

@ -1250,14 +1250,14 @@ pub const SSL_VERIFY_NONE: c_int = 0;
pub const SSL_VERIFY_PEER: c_int = 1;
pub const SSL_VERIFY_FAIL_IF_NO_PEER_CERT: c_int = 2;
#[cfg(not(any(libressl261, ossl101)))]
#[cfg(not(any(libressl261, libressl262, ossl101)))]
pub const SSL_OP_TLSEXT_PADDING: c_ulong = 0x00000010;
#[cfg(libressl261)]
#[cfg(any(libressl261, libressl262))]
pub const SSL_OP_TLSEXT_PADDING: c_ulong = 0x0;
pub const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: c_ulong = 0x00000800;
#[cfg(not(libressl261))]
#[cfg(not(any(libressl261, libressl262)))]
pub const SSL_OP_CRYPTOPRO_TLSEXT_BUG: c_ulong = 0x80000000;
#[cfg(libressl261)]
#[cfg(any(libressl261, libressl262))]
pub const SSL_OP_CRYPTOPRO_TLSEXT_BUG: c_ulong = 0x0;
pub const SSL_OP_LEGACY_SERVER_CONNECT: c_ulong = 0x00000004;
#[cfg(not(libressl))]

View File

@ -345,9 +345,9 @@ pub const SSL_CTRL_OPTIONS: c_int = 32;
pub const SSL_CTRL_CLEAR_OPTIONS: c_int = 77;
pub const SSL_CTRL_SET_ECDH_AUTO: c_int = 94;
#[cfg(libressl261)]
#[cfg(any(libressl261, libressl262))]
pub const SSL_OP_ALL: c_ulong = 0x4;
#[cfg(not(libressl261))]
#[cfg(not(any(libressl261, libressl262)))]
pub const SSL_OP_ALL: c_ulong = 0x80000014;
pub const SSL_OP_CISCO_ANYCONNECT: c_ulong = 0x0;
pub const SSL_OP_NO_COMPRESSION: c_ulong = 0x0;
@ -360,9 +360,9 @@ pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x0;
pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x0;
pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x0;
pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x0;
#[cfg(libressl261)]
#[cfg(any(libressl261, libressl262))]
pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x0;
#[cfg(not(libressl261))]
#[cfg(not(any(libressl261, libressl262)))]
pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00080000;
pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00100000;
pub const SSL_OP_NO_SSLv2: c_ulong = 0x0;

View File

@ -63,11 +63,11 @@ foreign_type! {
impl fmt::Display for Asn1GeneralizedTimeRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe {
let mem_bio = try!(MemBio::new());
try!(cvt(ffi::ASN1_GENERALIZEDTIME_print(
let mem_bio = MemBio::new()?;
cvt(ffi::ASN1_GENERALIZEDTIME_print(
mem_bio.as_ptr(),
self.as_ptr(),
)));
))?;
write!(f, "{}", str::from_utf8_unchecked(mem_bio.get_buf()))
}
}
@ -96,8 +96,8 @@ foreign_type! {
impl fmt::Display for Asn1TimeRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
unsafe {
let mem_bio = try!(MemBio::new());
try!(cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.as_ptr())));
let mem_bio = MemBio::new()?;
cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.as_ptr()))?;
write!(f, "{}", str::from_utf8_unchecked(mem_bio.get_buf()))
}
}
@ -108,7 +108,7 @@ impl Asn1Time {
ffi::init();
unsafe {
let handle = try!(cvt_p(ffi::X509_gmtime_adj(ptr::null_mut(), period)));
let handle = cvt_p(ffi::X509_gmtime_adj(ptr::null_mut(), period))?;
Ok(Asn1Time::from_ptr(handle))
}
}
@ -279,7 +279,7 @@ impl fmt::Display for Asn1ObjectRef {
self.as_ptr(),
0,
);
let s = try!(str::from_utf8(&buf[..len as usize]).map_err(|_| fmt::Error));
let s = str::from_utf8(&buf[..len as usize]).map_err(|_| fmt::Error)?;
fmt.write_str(s)
}
}

View File

@ -23,10 +23,10 @@ impl<'a> MemBioSlice<'a> {
assert!(buf.len() <= c_int::max_value() as usize);
let bio = unsafe {
try!(cvt_p(BIO_new_mem_buf(
cvt_p(BIO_new_mem_buf(
buf.as_ptr() as *const _,
buf.len() as c_int,
)))
))?
};
Ok(MemBioSlice(bio, PhantomData))
@ -51,7 +51,7 @@ impl MemBio {
pub fn new() -> Result<MemBio, ErrorStack> {
ffi::init();
let bio = unsafe { try!(cvt_p(ffi::BIO_new(ffi::BIO_s_mem()))) };
let bio = unsafe { cvt_p(ffi::BIO_new(ffi::BIO_s_mem()))? };
Ok(MemBio(bio))
}

View File

@ -1,3 +1,29 @@
//! BigNum implementation
//!
//! Large numbers are important for a cryptographic library. OpenSSL implementation
//! of BigNum uses dynamically assigned memory to store an array of bit chunks. This
//! allows numbers of any size to be compared and mathematical functions performed.
//!
//! OpenSSL wiki describes the [`BIGNUM`] data structure.
//!
//! # Examples
//!
//! ```
//! use openssl::bn::BigNum;
//! use openssl::error::ErrorStack;
//!
//! fn bignums() -> Result< (), ErrorStack > {
//! let a = BigNum::new()?; // a = 0
//! let b = BigNum::from_dec_str("1234567890123456789012345")?;
//! let c = &a * &b;
//! assert_eq!(a,c);
//! Ok(())
//! }
//! # fn main() {
//! # bignums();
//! # }
//!
//! [`BIGNUM`]: https://wiki.openssl.org/index.php/Manual:Bn_internal(3)
use ffi;
use foreign_types::{ForeignType, ForeignTypeRef};
use libc::c_int;
@ -45,12 +71,26 @@ foreign_type! {
type CType = ffi::BN_CTX;
fn drop = ffi::BN_CTX_free;
/// Temporary storage for BigNums on the secure heap
///
/// BigNum values are stored dynamically and therefore can be expensive
/// to allocate. BigNumContext and the OpenSSL [`BN_CTX`] structure are used
/// internally when passing BigNum values between subroutines.
///
/// [`BN_CTX`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_CTX_new.html
pub struct BigNumContext;
/// Reference to [`BigNumContext`]
///
/// [`BigNumContext`]: struct.BigNumContext.html
pub struct BigNumContextRef;
}
impl BigNumContext {
/// Returns a new `BigNumContext`.
///
/// See OpenSSL documentation at [`BN_CTX_new`].
///
/// [`BN_CTX_new`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_CTX_new.html
pub fn new() -> Result<BigNumContext, ErrorStack> {
unsafe {
ffi::init();
@ -59,30 +99,84 @@ impl BigNumContext {
}
}
foreign_type! {
type CType = ffi::BIGNUM;
fn drop = ffi::BN_free;
/// Dynamically sized large number impelementation
///
/// Perform large number mathematics. Create a new BigNum
/// with [`new`]. Perform stanard mathematics on large numbers using
/// methods from [`Dref<Target = BigNumRef>`]
///
/// OpenSSL documenation at [`BN_new`].
///
/// [`new`]: struct.BigNum.html#method.new
/// [`Dref<Target = BigNumRef>`]: struct.BigNum.html#deref-methods
/// [`BN_new`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_new.html
///
/// # Examples
/// ```
/// use openssl::bn::BigNum;
/// # use openssl::error::ErrorStack;
/// # fn bignums() -> Result< (), ErrorStack > {
/// let little_big = BigNum::from_u32(std::u32::MAX)?;
/// assert_eq!(*&little_big.num_bytes(), 4);
/// # Ok(())
/// # }
/// # fn main () { bignums(); }
/// ```
pub struct BigNum;
/// Reference to a [`BigNum`]
///
/// [`BigNum`]: struct.BigNum.html
pub struct BigNumRef;
}
impl BigNumRef {
/// Erases the memory used by this `BigNum`, resetting its value to 0.
///
/// This can be used to destroy sensitive data such as keys when they are no longer needed.
///
/// OpenSSL documentation at [`BN_clear`]
///
/// [`BN_clear`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_clear.html
pub fn clear(&mut self) {
unsafe { ffi::BN_clear(self.as_ptr()) }
}
/// Adds a `u32` to `self`.
///
/// OpenSSL documentation at [`BN_add_word`]
///
/// [`BN_add_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_add_word.html
pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) }
}
/// Subtracts a `u32` from `self`.
///
/// OpenSSL documentation at [`BN_sub_word`]
///
/// [`BN_sub_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sub_word.html
pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) }
}
/// Multiplies a `u32` by `self`.
///
/// OpenSSL documentation at [`BN_mul_word`]
///
/// [`BN_mul_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mul_word.html
pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) }
}
/// Divides `self` by a `u32`, returning the remainder.
///
/// OpenSSL documentation at [`BN_div_word`]
///
/// [`BN_div_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div_word.html
pub fn div_word(&mut self, w: u32) -> Result<u64, ErrorStack> {
unsafe {
let r = ffi::BN_div_word(self.as_ptr(), w.into());
@ -95,6 +189,10 @@ impl BigNumRef {
}
/// Returns the result of `self` modulo `w`.
///
/// OpenSSL documentation at [`BN_mod_word`]
///
/// [`BN_mod_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_word.html
pub fn mod_word(&self, w: u32) -> Result<u64, ErrorStack> {
unsafe {
let r = ffi::BN_mod_word(self.as_ptr(), w.into());
@ -106,13 +204,21 @@ impl BigNumRef {
}
}
/// Places a cryptographically-secure pseudo-random number nonnegative
/// Places a cryptographically-secure pseudo-random nonnegative
/// number less than `self` in `rnd`.
///
/// OpenSSL documentation at [`BN_rand_range`]
///
/// [`BN_rand_range`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rand_range.html
pub fn rand_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_rand_range(rnd.as_ptr(), self.as_ptr())).map(|_| ()) }
}
/// The cryptographically weak counterpart to `rand_in_range`.
///
/// OpenSSL documentation at [`BN_pseudo_rand_range`]
///
/// [`BN_pseudo_rand_range`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_pseudo_rand_range.html
pub fn pseudo_rand_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_pseudo_rand_range(rnd.as_ptr(), self.as_ptr())).map(|_| ()) }
}
@ -120,6 +226,10 @@ impl BigNumRef {
/// Sets bit `n`. Equivalent to `self |= (1 << n)`.
///
/// When setting a bit outside of `self`, it is expanded.
///
/// OpenSSL documentation at [`BN_set_bit`]
///
/// [`BN_set_bit`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_set_bit.html
pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_set_bit(self.as_ptr(), n.into())).map(|_| ()) }
}
@ -127,11 +237,19 @@ impl BigNumRef {
/// Clears bit `n`, setting it to 0. Equivalent to `self &= ~(1 << n)`.
///
/// When clearing a bit outside of `self`, an error is returned.
///
/// OpenSSL documentation at [`BN_clear_bit`]
///
/// [`BN_clear_bit`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_clear_bit.html
pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_clear_bit(self.as_ptr(), n.into())).map(|_| ()) }
}
/// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise.
///
/// OpenSSL documentation at [`BN_is_bit_set`]
///
/// [`BN_is_bit_set`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_bit_set.html
pub fn is_bit_set(&self, n: i32) -> bool {
unsafe { ffi::BN_is_bit_set(self.as_ptr(), n.into()) == 1 }
}
@ -139,51 +257,93 @@ impl BigNumRef {
/// Truncates `self` to the lowest `n` bits.
///
/// An error occurs if `self` is already shorter than `n` bits.
///
/// OpenSSL documentation at [`BN_mask_bits`]
///
/// [`BN_mask_bits`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mask_bits.html
pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ()) }
}
/// Places `a << 1` in `self`.
/// Places `a << 1` in `self`. Equivalent to `self * 2`.
///
/// OpenSSL documentation at [`BN_lshift1`]
///
/// [`BN_lshift1`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_lshift1.html
pub fn lshift1(&mut self, a: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_lshift1(self.as_ptr(), a.as_ptr())).map(|_| ()) }
}
/// Places `a >> 1` in `self`.
/// Places `a >> 1` in `self`. Equivalent to `self / 2`.
///
/// OpenSSL documentation at [`BN_rshift1`]
///
/// [`BN_rshift1`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rshift1.html
pub fn rshift1(&mut self, a: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_rshift1(self.as_ptr(), a.as_ptr())).map(|_| ()) }
}
/// Places `a + b` in `self`.
/// Places `a + b` in `self`. [`core::ops::Add`] is also implemented for `BigNumRef`.
///
/// OpenSSL documentation at [`BN_add`]
///
/// [`core::ops::Add`]: struct.BigNumRef.html#method.add
/// [`BN_add`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_add.html
pub fn checked_add(&mut self, a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_add(self.as_ptr(), a.as_ptr(), b.as_ptr())).map(|_| ()) }
}
/// Places `a - b` in `self`.
/// Places `a - b` in `self`. [`core::ops::Sub`] is also implemented for `BigNumRef`.
///
/// OpenSSL documentation at [`BN_sub`]
///
/// [`core::ops::Sub`]: struct.BigNumRef.html#method.sub
/// [`BN_sub`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sub.html
pub fn checked_sub(&mut self, a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_sub(self.as_ptr(), a.as_ptr(), b.as_ptr())).map(|_| ()) }
}
/// Places `a << n` in `self`.
/// Places `a << n` in `self`. Equivalent to `a * 2 ^ n`.
///
/// OpenSSL documentation at [`BN_lshift`]
///
/// [`BN_lshift`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_lshift.html
pub fn lshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_lshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) }
}
/// Places `a >> n` in `self`.
/// Places `a >> n` in `self`. Equivalent to `a / 2 ^ n`.
///
/// OpenSSL documentation at [`BN_rshift`]
///
/// [`BN_rshift`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rshift.html
pub fn rshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_rshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) }
}
/// Creates a new BigNum with the same value.
///
/// OpenSSL documentation at [`BN_dup`]
///
/// [`BN_dup`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_dup.html
pub fn to_owned(&self) -> Result<BigNum, ErrorStack> {
unsafe { cvt_p(ffi::BN_dup(self.as_ptr())).map(|b| BigNum::from_ptr(b)) }
}
/// Sets the sign of `self`.
/// Sets the sign of `self`. Pass true to set `self` to a negative. False sets
/// `self` positive.
pub fn set_negative(&mut self, negative: bool) {
unsafe { ffi::BN_set_negative(self.as_ptr(), negative as c_int) }
}
/// Compare the absolute values of `self` and `oth`.
///
/// OpenSSL documentation at [`BN_ucmp`]
///
/// [`BN_ucmp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_ucmp.html
///
/// # Examples
///
/// ```
/// # use openssl::bn::BigNum;
/// # use std::cmp::Ordering;
@ -196,6 +356,7 @@ impl BigNumRef {
unsafe { ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0) }
}
/// Returns `true` if `self` is negative.
pub fn is_negative(&self) -> bool {
self._is_negative()
}
@ -211,11 +372,15 @@ impl BigNumRef {
}
/// Returns the number of significant bits in `self`.
///
/// OpenSSL documentation at [`BN_num_bits`]
///
/// [`BN_num_bits`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_num_bits.html
pub fn num_bits(&self) -> i32 {
unsafe { ffi::BN_num_bits(self.as_ptr()) as i32 }
}
/// Returns the size of `self` in bytes.
/// Returns the size of `self` in bytes. Implemented natively.
pub fn num_bytes(&self) -> i32 {
(self.num_bits() + 7) / 8
}
@ -225,8 +390,28 @@ impl BigNumRef {
/// # Parameters
///
/// * `bits`: Length of the number in bits.
/// * `msb`: The desired properties of the number.
/// * `msb`: The desired properties of the most significant bit. See [`constants`].
/// * `odd`: If `true`, the generated number will be odd.
///
/// # Examples
///
/// ```
/// use openssl::bn::{BigNum,MSB_MAYBE_ZERO};
/// use openssl::error::ErrorStack;
///
/// fn generate_random() -> Result< BigNum, ErrorStack > {
/// let mut big = BigNum::new()?;
///
/// // Generates a 128-bit odd random number
/// big.rand(128, MSB_MAYBE_ZERO, true);
/// Ok((big))
/// }
/// ```
///
/// OpenSSL documentation at [`BN_rand`]
///
/// [`constants`]: index.html#constants
/// [`BN_rand`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rand.html
pub fn rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::BN_rand(
@ -238,7 +423,11 @@ impl BigNumRef {
}
}
/// The cryptographically weak counterpart to `rand`.
/// The cryptographically weak counterpart to `rand`. Not suitable for key generation.
///
/// OpenSSL documentation at [`BN_psuedo_rand`]
///
/// [`BN_psuedo_rand`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_pseudo_rand.html
pub fn pseudo_rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> {
unsafe {
cvt(ffi::BN_pseudo_rand(
@ -258,6 +447,25 @@ impl BigNumRef {
/// * `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`).
///
/// # Examples
///
/// ```
/// use openssl::bn::BigNum;
/// use openssl::error::ErrorStack;
///
/// fn generate_weak_prime() -> Result< BigNum, ErrorStack > {
/// let mut big = BigNum::new()?;
///
/// // Generates a 128-bit simple prime number
/// big.generate_prime(128, false, None, None);
/// Ok((big))
/// }
/// ```
///
/// OpenSSL documentation at [`BN_generate_prime_ex`]
///
/// [`BN_generate_prime_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_generate_prime_ex.html
pub fn generate_prime(
&mut self,
bits: i32,
@ -278,6 +486,12 @@ impl BigNumRef {
}
/// Places the result of `a * b` in `self`.
/// [`core::ops::Mul`] is also implemented for `BigNumRef`.
///
/// OpenSSL documentation at [`BN_mul`]
///
/// [`core::ops::Mul`]: struct.BigNumRef.html#method.mul
/// [`BN_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mul.html
pub fn checked_mul(
&mut self,
a: &BigNumRef,
@ -294,7 +508,13 @@ impl BigNumRef {
}
}
/// Places the result of `a / b` in `self`.
/// Places the result of `a / b` in `self`. The remainder is discarded.
/// [`core::ops::Div`] is also implemented for `BigNumRef`.
///
/// OpenSSL documentation at [`BN_div`]
///
/// [`core::ops::Div`]: struct.BigNumRef.html#method.div
/// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html
pub fn checked_div(
&mut self,
a: &BigNumRef,
@ -313,6 +533,10 @@ impl BigNumRef {
}
/// Places the result of `a % b` in `self`.
///
/// OpenSSL documentation at [`BN_div`]
///
/// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html
pub fn checked_rem(
&mut self,
a: &BigNumRef,
@ -331,6 +555,10 @@ impl BigNumRef {
}
/// Places the result of `a / b` in `self` and `a % b` in `rem`.
///
/// OpenSSL documentation at [`BN_div`]
///
/// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html
pub fn div_rem(
&mut self,
rem: &mut BigNumRef,
@ -350,11 +578,20 @@ impl BigNumRef {
}
/// Places the result of `a²` in `self`.
///
/// OpenSSL documentation at [`BN_sqr`]
///
/// [`BN_sqr`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sqr.html
pub fn sqr(&mut self, a: &BigNumRef, ctx: &mut BigNumContextRef) -> Result<(), ErrorStack> {
unsafe { cvt(ffi::BN_sqr(self.as_ptr(), a.as_ptr(), ctx.as_ptr())).map(|_| ()) }
}
/// Places the result of `a mod m` in `self`.
/// Places the result of `a mod m` in `self`. As opposed to `div_rem`
/// the result is non-negative.
///
/// OpenSSL documentation at [`BN_nnmod`]
///
/// [`BN_nnmod`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_nnmod.html
pub fn nnmod(
&mut self,
a: &BigNumRef,
@ -372,6 +609,10 @@ impl BigNumRef {
}
/// Places the result of `(a + b) mod m` in `self`.
///
/// OpenSSL documentation at [`BN_mod_add`]
///
/// [`BN_mod_add`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_add.html
pub fn mod_add(
&mut self,
a: &BigNumRef,
@ -391,6 +632,10 @@ impl BigNumRef {
}
/// Places the result of `(a - b) mod m` in `self`.
///
/// OpenSSL documentation at [`BN_mod_sub`]
///
/// [`BN_mod_sub`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_sub.html
pub fn mod_sub(
&mut self,
a: &BigNumRef,
@ -410,6 +655,10 @@ impl BigNumRef {
}
/// Places the result of `(a * b) mod m` in `self`.
///
/// OpenSSL documentation at [`BN_mod_mul`]
///
/// [`BN_mod_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_mul.html
pub fn mod_mul(
&mut self,
a: &BigNumRef,
@ -429,6 +678,10 @@ impl BigNumRef {
}
/// Places the result of `a² mod m` in `self`.
///
/// OpenSSL documentation at [`BN_mod_sqr`]
///
/// [`BN_mod_sqr`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_sqr.html
pub fn mod_sqr(
&mut self,
a: &BigNumRef,
@ -446,6 +699,10 @@ impl BigNumRef {
}
/// Places the result of `a^p` in `self`.
///
/// OpenSSL documentation at [`BN_exp`]
///
/// [`BN_exp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_exp.html
pub fn exp(
&mut self,
a: &BigNumRef,
@ -463,6 +720,10 @@ impl BigNumRef {
}
/// Places the result of `a^p mod m` in `self`.
///
/// OpenSSL documentation at [`BN_mod_exp`]
///
/// [`BN_mod_exp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_exp.html
pub fn mod_exp(
&mut self,
a: &BigNumRef,
@ -499,6 +760,10 @@ impl BigNumRef {
}
/// Places the greatest common denominator of `a` and `b` in `self`.
///
/// OpenSSL documentation at [`BN_gcd`]
///
/// [`BN_gcd`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_gcd.html
pub fn gcd(
&mut self,
a: &BigNumRef,
@ -519,7 +784,14 @@ impl BigNumRef {
///
/// Performs a Miller-Rabin probabilistic primality test with `checks` iterations.
///
/// OpenSSL documentation at [`BN_is_prime_ex`]
///
/// [`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_prime_ex.html
///
/// # 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, ctx: &mut BigNumContextRef) -> Result<bool, ErrorStack> {
unsafe {
cvt_n(ffi::BN_is_prime_ex(
@ -537,6 +809,10 @@ impl BigNumRef {
/// Then, like `is_prime`, performs a Miller-Rabin probabilistic primality test with `checks`
/// iterations.
///
/// OpenSSL documentation at [`BN_is_prime_fasttest_ex`]
///
/// [`BN_is_prime_fasttest_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_prime_fasttest_ex.html
///
/// # Return Value
///
/// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`.
@ -589,7 +865,7 @@ impl BigNumRef {
/// ```
pub fn to_dec_str(&self) -> Result<OpensslString, ErrorStack> {
unsafe {
let buf = try!(cvt_p(ffi::BN_bn2dec(self.as_ptr())));
let buf = cvt_p(ffi::BN_bn2dec(self.as_ptr()))?;
Ok(OpensslString::from_ptr(buf))
}
}
@ -604,7 +880,7 @@ impl BigNumRef {
/// ```
pub fn to_hex_str(&self) -> Result<OpensslString, ErrorStack> {
unsafe {
let buf = try!(cvt_p(ffi::BN_bn2hex(self.as_ptr())));
let buf = cvt_p(ffi::BN_bn2hex(self.as_ptr()))?;
Ok(OpensslString::from_ptr(buf))
}
}
@ -618,25 +894,21 @@ impl BigNumRef {
}
}
foreign_type! {
type CType = ffi::BIGNUM;
fn drop = ffi::BN_free;
pub struct BigNum;
pub struct BigNumRef;
}
impl BigNum {
/// Creates a new `BigNum` with the value 0.
pub fn new() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
let v = try!(cvt_p(ffi::BN_new()));
let v = cvt_p(ffi::BN_new())?;
Ok(BigNum::from_ptr(v))
}
}
/// Creates a new `BigNum` with the given value.
///
/// OpenSSL documentation at [`BN_set_word`]
///
/// [`BN_set_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_set_word.html
pub fn from_u32(n: u32) -> Result<BigNum, ErrorStack> {
BigNum::new().and_then(|v| unsafe {
cvt(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)).map(|_| v)
@ -644,27 +916,43 @@ impl BigNum {
}
/// Creates a `BigNum` from a decimal string.
///
/// OpenSSL documentation at [`BN_dec2bn`]
///
/// [`BN_dec2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_dec2bn.html
pub fn from_dec_str(s: &str) -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
let c_str = CString::new(s.as_bytes()).unwrap();
let mut bn = ptr::null_mut();
try!(cvt(ffi::BN_dec2bn(&mut bn, c_str.as_ptr() as *const _)));
cvt(ffi::BN_dec2bn(&mut bn, c_str.as_ptr() as *const _))?;
Ok(BigNum::from_ptr(bn))
}
}
/// Creates a `BigNum` from a hexadecimal string.
///
/// OpenSSL documentation at [`BN_hex2bn`]
///
/// [`BN_hex2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_hex2bn.html
pub fn from_hex_str(s: &str) -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
let c_str = CString::new(s.as_bytes()).unwrap();
let mut bn = ptr::null_mut();
try!(cvt(ffi::BN_hex2bn(&mut bn, c_str.as_ptr() as *const _)));
cvt(ffi::BN_hex2bn(&mut bn, c_str.as_ptr() as *const _))?;
Ok(BigNum::from_ptr(bn))
}
}
/// Returns a constant used in IKE as defined in [`RFC 2409`]. This prime number is in
/// the order of magnitude of `2 ^ 768`. This number is used during calculated key
/// exchanges such as Diffie-Hellman. This number is labeled Oakley group id 1.
///
/// OpenSSL documentation at [`BN_get_rfc2409_prime_768`]
///
/// [`RFC 2409`]: https://tools.ietf.org/html/rfc2409#page-21
/// [`BN_get_rfc2409_prime_768`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc2409_prime_768.html
pub fn get_rfc2409_prime_768() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
@ -672,6 +960,14 @@ impl BigNum {
}
}
/// Returns a constant used in IKE as defined in [`RFC 2409`]. This prime number is in
/// the order of magnitude of `2 ^ 1024`. This number is used during calculated key
/// exchanges such as Diffie-Hellman. This number is labeled Oakly group 2.
///
/// OpenSSL documentation at [`BN_get_rfc2409_prime_1024`]
///
/// [`RFC 2409`]: https://tools.ietf.org/html/rfc2409#page-21
/// [`BN_get_rfc2409_prime_1024`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc2409_prime_1024.html
pub fn get_rfc2409_prime_1024() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
@ -679,6 +975,14 @@ impl BigNum {
}
}
/// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order
/// of magnitude of `2 ^ 1536`. This number is used during calculated key
/// exchanges such as Diffie-Hellman. This number is labeled MODP group 5.
///
/// OpenSSL documentation at [`BN_get_rfc3526_prime_1536`]
///
/// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-3
/// [`BN_get_rfc3526_prime_1536`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_1536.html
pub fn get_rfc3526_prime_1536() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
@ -686,6 +990,14 @@ impl BigNum {
}
}
/// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order
/// of magnitude of `2 ^ 2048`. This number is used during calculated key
/// exchanges such as Diffie-Hellman. This number is labeled MODP group 14.
///
/// OpenSSL documentation at [`BN_get_rfc3526_prime_2048`]
///
/// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-3
/// [`BN_get_rfc3526_prime_2048`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_2048.html
pub fn get_rfc3526_prime_2048() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
@ -693,6 +1005,14 @@ impl BigNum {
}
}
/// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order
/// of magnitude of `2 ^ 3072`. This number is used during calculated key
/// exchanges such as Diffie-Hellman. This number is labeled MODP group 15.
///
/// OpenSSL documentation at [`BN_get_rfc3526_prime_3072`]
///
/// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-4
/// [`BN_get_rfc3526_prime_3072`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_3072.html
pub fn get_rfc3526_prime_3072() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
@ -700,6 +1020,14 @@ impl BigNum {
}
}
/// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order
/// of magnitude of `2 ^ 4096`. This number is used during calculated key
/// exchanges such as Diffie-Hellman. This number is labeled MODP group 16.
///
/// OpenSSL documentation at [`BN_get_rfc3526_prime_4096`]
///
/// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-4
/// [`BN_get_rfc3526_prime_4096`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_4096.html
pub fn get_rfc3526_prime_4096() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
@ -707,6 +1035,14 @@ impl BigNum {
}
}
/// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order
/// of magnitude of `2 ^ 6144`. This number is used during calculated key
/// exchanges such as Diffie-Hellman. This number is labeled MODP group 17.
///
/// OpenSSL documentation at [`BN_get_rfc3526_prime_6144`]
///
/// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-6
/// [`BN_get_rfc3526_prime_6144`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_6144.html
pub fn get_rfc3526_prime_6144() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
@ -714,6 +1050,14 @@ impl BigNum {
}
}
/// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order
/// of magnitude of `2 ^ 8192`. This number is used during calculated key
/// exchanges such as Diffie-Hellman. This number is labeled MODP group 18.
///
/// OpenSSL documentation at [`BN_get_rfc3526_prime_8192`]
///
/// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-6
/// [`BN_get_rfc3526_prime_8192`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_8192.html
pub fn get_rfc3526_prime_8192() -> Result<BigNum, ErrorStack> {
unsafe {
ffi::init();
@ -723,6 +1067,10 @@ impl BigNum {
/// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length.
///
/// OpenSSL documentation at [`BN_bin2bn`]
///
/// [`BN_bin2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_bin2bn.html
///
/// ```
/// # use openssl::bn::BigNum;
/// let bignum = BigNum::from_slice(&[0x12, 0x00, 0x34]).unwrap();

View File

@ -1,4 +1,9 @@
//! CMS archive
//! SMIME implementation using CMS
//!
//! CMS (PKCS#7) is an encyption standard. It allows signing and ecrypting data using
//! X.509 certificates. The OpenSSL implementation of CMS is used in email encryption
//! generated from a `Vec` of bytes. This `Vec` follows the smime protocol standards.
//! Data accepted by this module will be smime type `enveloped-data`.
use ffi;
use foreign_types::{ForeignType, ForeignTypeRef};
@ -17,26 +22,43 @@ foreign_type! {
type CType = ffi::CMS_ContentInfo;
fn drop = ffi::CMS_ContentInfo_free;
/// High level CMS wrapper
///
/// CMS supports nesting various types of data, including signatures, certificates,
/// encrypted data, smime messages (encrypted email), and data digest. The ContentInfo
/// content type is the encapsulation of all those content types. [`RFC 5652`] describes
/// CMS and OpenSSL follows this RFC's implmentation.
///
/// [`RFC 5652`]: https://tools.ietf.org/html/rfc5652#page-6
pub struct CmsContentInfo;
/// Reference to [`CMSContentInfo`]
///
/// [`CMSContentInfo`]:struct.CmsContentInfo.html
pub struct CmsContentInfoRef;
}
impl CmsContentInfoRef {
/// Given the sender's private key, `pkey` and the recipient's certificiate, `cert`,
/// decrypt the data in `self`.
///
/// OpenSSL documentation at [`CMS_decrypt`]
///
/// [`CMS_decrypt`]: https://www.openssl.org/docs/man1.1.0/crypto/CMS_decrypt.html
pub fn decrypt(&self, pkey: &PKeyRef, cert: &X509) -> Result<Vec<u8>, ErrorStack> {
unsafe {
let pkey = pkey.as_ptr();
let cert = cert.as_ptr();
let out = try!(MemBio::new());
let out = MemBio::new()?;
let flags: u32 = 0;
try!(cvt(ffi::CMS_decrypt(
cvt(ffi::CMS_decrypt(
self.as_ptr(),
pkey,
cert,
ptr::null_mut(),
out.as_ptr(),
flags.into(),
)));
))?;
Ok(out.get_buf().to_owned())
}
@ -45,14 +67,19 @@ impl CmsContentInfoRef {
}
impl CmsContentInfo {
/// Parses a smime formatted `vec` of bytes into a `CmsContentInfo`.
///
/// OpenSSL documentation at [`SMIME_read_CMS`]
///
/// [`SMIME_read_CMS`]: https://www.openssl.org/docs/man1.0.2/crypto/SMIME_read_CMS.html
pub fn smime_read_cms(smime: &[u8]) -> Result<CmsContentInfo, ErrorStack> {
unsafe {
let bio = try!(MemBioSlice::new(smime));
let bio = MemBioSlice::new(smime)?;
let cms = try!(cvt_p(ffi::SMIME_read_CMS(
let cms = cvt_p(ffi::SMIME_read_CMS(
bio.as_ptr(),
ptr::null_mut(),
)));
))?;
Ok(CmsContentInfo::from_ptr(cms))
}

View File

@ -1,3 +1,4 @@
//! Interface for processing OpenSSL configuration files.
use ffi;
use cvt_p;
@ -6,17 +7,22 @@ use error::ErrorStack;
pub struct ConfMethod(*mut ffi::CONF_METHOD);
impl ConfMethod {
/// Retrieve handle to the default OpenSSL configuration file processing function.
pub fn default() -> ConfMethod {
unsafe {
ffi::init();
// `NCONF` stands for "New Conf", as described in crypto/conf/conf_lib.c. This is
// a newer API than the "CONF classic" functions.
ConfMethod(ffi::NCONF_default())
}
}
/// Construct from raw pointer.
pub unsafe fn from_ptr(ptr: *mut ffi::CONF_METHOD) -> ConfMethod {
ConfMethod(ptr)
}
/// Convert to raw pointer.
pub fn as_ptr(&self) -> *mut ffi::CONF_METHOD {
self.0
}
@ -31,6 +37,15 @@ foreign_type! {
}
impl Conf {
/// Create a configuration parser.
///
/// # Examples
///
/// ```
/// use openssl::conf::{Conf, ConfMethod};
///
/// let conf = Conf::new(ConfMethod::default());
/// ```
pub fn new(method: ConfMethod) -> Result<Conf, ErrorStack> {
unsafe { cvt_p(ffi::NCONF_new(method.as_ptr())).map(Conf) }
}

View File

@ -24,13 +24,13 @@ impl DhRef {
impl Dh {
pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result<Dh, ErrorStack> {
unsafe {
let dh = Dh(try!(cvt_p(ffi::DH_new())));
try!(cvt(compat::DH_set0_pqg(
let dh = Dh(cvt_p(ffi::DH_new())?);
cvt(compat::DH_set0_pqg(
dh.0,
p.as_ptr(),
q.as_ptr(),
g.as_ptr(),
)));
))?;
mem::forget((p, g, q));
Ok(dh)
}

View File

@ -84,8 +84,8 @@ impl Dsa {
pub fn generate(bits: u32) -> Result<Dsa, ErrorStack> {
ffi::init();
unsafe {
let dsa = Dsa(try!(cvt_p(ffi::DSA_new())));
try!(cvt(ffi::DSA_generate_parameters_ex(
let dsa = Dsa(cvt_p(ffi::DSA_new())?);
cvt(ffi::DSA_generate_parameters_ex(
dsa.0,
bits as c_int,
ptr::null(),
@ -93,8 +93,8 @@ impl Dsa {
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
)));
try!(cvt(ffi::DSA_generate_key(dsa.0)));
))?;
cvt(ffi::DSA_generate_key(dsa.0))?;
Ok(dsa)
}
}
@ -111,16 +111,16 @@ impl Dsa {
{
ffi::init();
let mut cb = CallbackState::new(pass_cb);
let mem_bio = try!(MemBioSlice::new(buf));
let mem_bio = MemBioSlice::new(buf)?;
unsafe {
let cb_ptr = &mut cb as *mut _ as *mut c_void;
let dsa = try!(cvt_p(ffi::PEM_read_bio_DSAPrivateKey(
let dsa = cvt_p(ffi::PEM_read_bio_DSAPrivateKey(
mem_bio.as_ptr(),
ptr::null_mut(),
Some(invoke_passwd_cb_old::<F>),
cb_ptr,
)));
))?;
Ok(Dsa(dsa))
}
}

View File

@ -262,12 +262,12 @@ impl EcPointRef {
ctx: &mut BigNumContextRef,
) -> Result<bool, ErrorStack> {
unsafe {
let res = try!(cvt_n(ffi::EC_POINT_cmp(
let res = cvt_n(ffi::EC_POINT_cmp(
group.as_ptr(),
self.as_ptr(),
other.as_ptr(),
ctx.as_ptr(),
)));
))?;
Ok(res == 0)
}
}
@ -323,15 +323,15 @@ impl EcPoint {
buf: &[u8],
ctx: &mut BigNumContextRef,
) -> Result<EcPoint, ErrorStack> {
let point = try!(EcPoint::new(group));
let point = EcPoint::new(group)?;
unsafe {
try!(cvt(ffi::EC_POINT_oct2point(
cvt(ffi::EC_POINT_oct2point(
group.as_ptr(),
point.as_ptr(),
buf.as_ptr(),
buf.len(),
ctx.as_ptr(),
)));
))?;
}
Ok(point)
}
@ -429,17 +429,17 @@ impl EcKey {
group: &EcGroupRef,
public_key: &EcPointRef,
) -> Result<EcKey, ErrorStack> {
let mut builder = try!(EcKeyBuilder::new());
try!(builder.set_group(group));
try!(builder.set_public_key(public_key));
let mut builder = EcKeyBuilder::new()?;
builder.set_group(group)?;
builder.set_public_key(public_key)?;
Ok(builder.build())
}
/// Generates a new public/private key pair on the specified curve.
pub fn generate(group: &EcGroupRef) -> Result<EcKey, ErrorStack> {
let mut builder = try!(EcKeyBuilder::new());
try!(builder.set_group(group));
try!(builder.generate_key());
let mut builder = EcKeyBuilder::new()?;
builder.set_group(group)?;
builder.generate_key()?;
Ok(builder.build())
}

View File

@ -35,9 +35,9 @@ impl fmt::Display for ErrorStack {
let mut first = true;
for err in &self.0 {
if !first {
try!(fmt.write_str(", "));
fmt.write_str(", ")?;
}
try!(write!(fmt, "{}", err));
write!(fmt, "{}", err)?;
first = false;
}
Ok(())
@ -197,18 +197,18 @@ impl fmt::Debug for Error {
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "error:{:08X}", self.code()));
write!(fmt, "error:{:08X}", self.code())?;
match self.library() {
Some(l) => try!(write!(fmt, ":{}", l)),
None => try!(write!(fmt, ":lib({})", ffi::ERR_GET_LIB(self.code()))),
Some(l) => write!(fmt, ":{}", l)?,
None => write!(fmt, ":lib({})", ffi::ERR_GET_LIB(self.code()))?,
}
match self.function() {
Some(f) => try!(write!(fmt, ":{}", f)),
None => try!(write!(fmt, ":func({})", ffi::ERR_GET_FUNC(self.code()))),
Some(f) => write!(fmt, ":{}", f)?,
None => write!(fmt, ":func({})", ffi::ERR_GET_FUNC(self.code()))?,
}
match self.reason() {
Some(r) => try!(write!(fmt, ":{}", r)),
None => try!(write!(fmt, ":reason({})", ffi::ERR_GET_FUNC(self.code()))),
Some(r) => write!(fmt, ":{}", r)?,
None => write!(fmt, ":reason({})", ffi::ERR_GET_FUNC(self.code()))?,
}
write!(
fmt,

View File

@ -104,7 +104,7 @@ impl Hasher {
pub fn new(ty: MessageDigest) -> Result<Hasher, ErrorStack> {
ffi::init();
let ctx = unsafe { try!(cvt_p(EVP_MD_CTX_new())) };
let ctx = unsafe { cvt_p(EVP_MD_CTX_new())? };
let mut h = Hasher {
ctx: ctx,
@ -112,7 +112,7 @@ impl Hasher {
type_: ty,
state: Finalized,
};
try!(h.init());
h.init()?;
Ok(h)
}
@ -120,12 +120,12 @@ impl Hasher {
match self.state {
Reset => return Ok(()),
Updated => {
try!(self.finish2());
self.finish2()?;
}
Finalized => (),
}
unsafe {
try!(cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _)));
cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))?;
}
self.state = Reset;
Ok(())
@ -134,14 +134,14 @@ impl Hasher {
/// Feeds data into the hasher.
pub fn update(&mut self, data: &[u8]) -> Result<(), ErrorStack> {
if self.state == Finalized {
try!(self.init());
self.init()?;
}
unsafe {
try!(cvt(ffi::EVP_DigestUpdate(
cvt(ffi::EVP_DigestUpdate(
self.ctx,
data.as_ptr() as *mut _,
data.len(),
)));
))?;
}
self.state = Updated;
Ok(())
@ -157,16 +157,16 @@ impl Hasher {
/// Unlike `finish`, this method does not allocate.
pub fn finish2(&mut self) -> Result<DigestBytes, ErrorStack> {
if self.state == Finalized {
try!(self.init());
self.init()?;
}
unsafe {
let mut len = ffi::EVP_MAX_MD_SIZE;
let mut buf = [0; ffi::EVP_MAX_MD_SIZE as usize];
try!(cvt(ffi::EVP_DigestFinal_ex(
cvt(ffi::EVP_DigestFinal_ex(
self.ctx,
buf.as_mut_ptr(),
&mut len,
)));
))?;
self.state = Finalized;
Ok(DigestBytes {
buf: buf,
@ -179,7 +179,7 @@ impl Hasher {
impl Write for Hasher {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
try!(self.update(buf));
self.update(buf)?;
Ok(buf.len())
}
@ -272,8 +272,8 @@ pub fn hash(t: MessageDigest, data: &[u8]) -> Result<Vec<u8>, ErrorStack> {
///
/// Unlike `hash`, this function does not allocate the return value.
pub fn hash2(t: MessageDigest, data: &[u8]) -> Result<DigestBytes, ErrorStack> {
let mut h = try!(Hasher::new(t));
try!(h.update(data));
let mut h = Hasher::new(t)?;
h.update(data)?;
h.finish2()
}

View File

@ -298,7 +298,7 @@ impl OcspRequestRef {
pub fn add_id(&mut self, id: OcspCertId) -> Result<&mut OcspOneReqRef, ErrorStack> {
unsafe {
let ptr = try!(cvt_p(ffi::OCSP_request_add0_id(self.as_ptr(), id.as_ptr())));
let ptr = cvt_p(ffi::OCSP_request_add0_id(self.as_ptr(), id.as_ptr()))?;
mem::forget(id);
Ok(OcspOneReqRef::from_ptr_mut(ptr))
}

View File

@ -34,19 +34,19 @@ impl Pkcs12Ref {
let mut cert = ptr::null_mut();
let mut chain = ptr::null_mut();
try!(cvt(ffi::PKCS12_parse(
cvt(ffi::PKCS12_parse(
self.as_ptr(),
pass.as_ptr(),
&mut pkey,
&mut cert,
&mut chain,
)));
))?;
let pkey = PKey::from_ptr(pkey);
let cert = X509::from_ptr(cert);
let chain = if chain.is_null() {
try!(Stack::new())
Stack::new()?
} else {
Stack::from_ptr(chain)
};

View File

@ -47,7 +47,7 @@ pub fn bytes_to_key(
let cipher = cipher.as_ptr();
let digest = digest.as_ptr();
let len = try!(cvt(ffi::EVP_BytesToKey(
let len = cvt(ffi::EVP_BytesToKey(
cipher,
digest,
salt_ptr,
@ -56,14 +56,14 @@ pub fn bytes_to_key(
count.into(),
ptr::null_mut(),
ptr::null_mut(),
)));
))?;
let mut key = vec![0; len as usize];
let iv_ptr = iv.as_mut().map(|v| v.as_mut_ptr()).unwrap_or(
ptr::null_mut(),
);
try!(cvt(ffi::EVP_BytesToKey(
cvt(ffi::EVP_BytesToKey(
cipher,
digest,
salt_ptr,
@ -72,7 +72,7 @@ pub fn bytes_to_key(
count as c_int,
key.as_mut_ptr(),
iv_ptr,
)));
))?;
Ok(KeyIvPair { key: key, iv: iv })
}

View File

@ -26,7 +26,7 @@ impl PKeyRef {
/// Returns a copy of the internal RSA key.
pub fn rsa(&self) -> Result<Rsa, ErrorStack> {
unsafe {
let rsa = try!(cvt_p(ffi::EVP_PKEY_get1_RSA(self.as_ptr())));
let rsa = cvt_p(ffi::EVP_PKEY_get1_RSA(self.as_ptr()))?;
Ok(Rsa::from_ptr(rsa))
}
}
@ -34,7 +34,7 @@ impl PKeyRef {
/// Returns a copy of the internal DSA key.
pub fn dsa(&self) -> Result<Dsa, ErrorStack> {
unsafe {
let dsa = try!(cvt_p(ffi::EVP_PKEY_get1_DSA(self.as_ptr())));
let dsa = cvt_p(ffi::EVP_PKEY_get1_DSA(self.as_ptr()))?;
Ok(Dsa::from_ptr(dsa))
}
}
@ -42,7 +42,7 @@ impl PKeyRef {
/// Returns a copy of the internal DH key.
pub fn dh(&self) -> Result<Dh, ErrorStack> {
unsafe {
let dh = try!(cvt_p(ffi::EVP_PKEY_get1_DH(self.as_ptr())));
let dh = cvt_p(ffi::EVP_PKEY_get1_DH(self.as_ptr()))?;
Ok(Dh::from_ptr(dh))
}
}
@ -50,7 +50,7 @@ impl PKeyRef {
/// Returns a copy of the internal elliptic curve key.
pub fn ec_key(&self) -> Result<EcKey, ErrorStack> {
unsafe {
let ec_key = try!(cvt_p(ffi::EVP_PKEY_get1_EC_KEY(self.as_ptr())));
let ec_key = cvt_p(ffi::EVP_PKEY_get1_EC_KEY(self.as_ptr()))?;
Ok(EcKey::from_ptr(ec_key))
}
}
@ -82,13 +82,13 @@ impl PKey {
/// Creates a new `PKey` containing an RSA key.
pub fn from_rsa(rsa: Rsa) -> Result<PKey, ErrorStack> {
unsafe {
let evp = try!(cvt_p(ffi::EVP_PKEY_new()));
let evp = cvt_p(ffi::EVP_PKEY_new())?;
let pkey = PKey(evp);
try!(cvt(ffi::EVP_PKEY_assign(
cvt(ffi::EVP_PKEY_assign(
pkey.0,
ffi::EVP_PKEY_RSA,
rsa.as_ptr() as *mut _,
)));
))?;
mem::forget(rsa);
Ok(pkey)
}
@ -97,13 +97,13 @@ impl PKey {
/// Creates a new `PKey` containing a DSA key.
pub fn from_dsa(dsa: Dsa) -> Result<PKey, ErrorStack> {
unsafe {
let evp = try!(cvt_p(ffi::EVP_PKEY_new()));
let evp = cvt_p(ffi::EVP_PKEY_new())?;
let pkey = PKey(evp);
try!(cvt(ffi::EVP_PKEY_assign(
cvt(ffi::EVP_PKEY_assign(
pkey.0,
ffi::EVP_PKEY_DSA,
dsa.as_ptr() as *mut _,
)));
))?;
mem::forget(dsa);
Ok(pkey)
}
@ -112,13 +112,13 @@ impl PKey {
/// Creates a new `PKey` containing a Diffie-Hellman key.
pub fn from_dh(dh: Dh) -> Result<PKey, ErrorStack> {
unsafe {
let evp = try!(cvt_p(ffi::EVP_PKEY_new()));
let evp = cvt_p(ffi::EVP_PKEY_new())?;
let pkey = PKey(evp);
try!(cvt(ffi::EVP_PKEY_assign(
cvt(ffi::EVP_PKEY_assign(
pkey.0,
ffi::EVP_PKEY_DH,
dh.as_ptr() as *mut _,
)));
))?;
mem::forget(dh);
Ok(pkey)
}
@ -127,13 +127,13 @@ impl PKey {
/// Creates a new `PKey` containing an elliptic curve key.
pub fn from_ec_key(ec_key: EcKey) -> Result<PKey, ErrorStack> {
unsafe {
let evp = try!(cvt_p(ffi::EVP_PKEY_new()));
let evp = cvt_p(ffi::EVP_PKEY_new())?;
let pkey = PKey(evp);
try!(cvt(ffi::EVP_PKEY_assign(
cvt(ffi::EVP_PKEY_assign(
pkey.0,
ffi::EVP_PKEY_EC,
ec_key.as_ptr() as *mut _,
)));
))?;
mem::forget(ec_key);
Ok(pkey)
}
@ -146,12 +146,12 @@ impl PKey {
pub fn hmac(key: &[u8]) -> Result<PKey, ErrorStack> {
unsafe {
assert!(key.len() <= c_int::max_value() as usize);
let key = try!(cvt_p(ffi::EVP_PKEY_new_mac_key(
let key = cvt_p(ffi::EVP_PKEY_new_mac_key(
ffi::EVP_PKEY_HMAC,
ptr::null_mut(),
key.as_ptr() as *const _,
key.len() as c_int,
)));
))?;
Ok(PKey(key))
}
}
@ -173,7 +173,7 @@ impl PKey {
unsafe {
ffi::init();
let mut cb = CallbackState::new(callback);
let bio = try!(MemBioSlice::new(der));
let bio = MemBioSlice::new(der)?;
cvt_p(ffi::d2i_PKCS8PrivateKey_bio(
bio.as_ptr(),
ptr::null_mut(),
@ -195,7 +195,7 @@ impl PKey {
) -> Result<PKey, ErrorStack> {
unsafe {
ffi::init();
let bio = try!(MemBioSlice::new(der));
let bio = MemBioSlice::new(der)?;
let passphrase = CString::new(passphrase).unwrap();
cvt_p(ffi::d2i_PKCS8PrivateKey_bio(
bio.as_ptr(),
@ -213,14 +213,14 @@ impl PKey {
{
ffi::init();
let mut cb = CallbackState::new(pass_cb);
let mem_bio = try!(MemBioSlice::new(buf));
let mem_bio = MemBioSlice::new(buf)?;
unsafe {
let evp = try!(cvt_p(ffi::PEM_read_bio_PrivateKey(
let evp = cvt_p(ffi::PEM_read_bio_PrivateKey(
mem_bio.as_ptr(),
ptr::null_mut(),
Some(invoke_passwd_cb_old::<F>),
&mut cb as *mut _ as *mut c_void,
)));
))?;
Ok(PKey::from_ptr(evp))
}
}
@ -240,7 +240,7 @@ unsafe impl Sync for PKeyCtx {}
impl PKeyCtx {
pub fn from_pkey(pkey: &PKeyRef) -> Result<PKeyCtx, ErrorStack> {
unsafe {
let evp = try!(cvt_p(ffi::EVP_PKEY_CTX_new(pkey.as_ptr(), ptr::null_mut())));
let evp = cvt_p(ffi::EVP_PKEY_CTX_new(pkey.as_ptr(), ptr::null_mut()))?;
Ok(PKeyCtx(evp))
}
}
@ -249,10 +249,10 @@ impl PKeyCtx {
impl PKeyCtxRef {
pub fn set_rsa_padding(&mut self, pad: Padding) -> Result<(), ErrorStack> {
unsafe {
try!(cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
self.as_ptr(),
pad.as_raw(),
)));
))?;
}
Ok(())
}
@ -260,25 +260,25 @@ impl PKeyCtxRef {
pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
let mut pad: c_int = 0;
unsafe {
try!(cvt(
cvt(
ffi::EVP_PKEY_CTX_get_rsa_padding(self.as_ptr(), &mut pad),
));
)?;
};
Ok(Padding::from_raw(pad))
}
pub fn derive_init(&mut self) -> Result<(), ErrorStack> {
unsafe {
try!(cvt(ffi::EVP_PKEY_derive_init(self.as_ptr())));
cvt(ffi::EVP_PKEY_derive_init(self.as_ptr()))?;
}
Ok(())
}
pub fn derive_set_peer(&mut self, peer: &PKeyRef) -> Result<(), ErrorStack> {
unsafe {
try!(cvt(
cvt(
ffi::EVP_PKEY_derive_set_peer(self.as_ptr(), peer.as_ptr()),
));
)?;
}
Ok(())
}
@ -286,20 +286,20 @@ impl PKeyCtxRef {
pub fn derive(&mut self) -> Result<Vec<u8>, ErrorStack> {
let mut len: size_t = 0;
unsafe {
try!(cvt(ffi::EVP_PKEY_derive(
cvt(ffi::EVP_PKEY_derive(
self.as_ptr(),
ptr::null_mut(),
&mut len,
)));
))?;
}
let mut key = vec![0u8; len];
unsafe {
try!(cvt(ffi::EVP_PKEY_derive(
cvt(ffi::EVP_PKEY_derive(
self.as_ptr(),
key.as_mut_ptr(),
&mut len,
)));
))?;
}
Ok(key)
}

View File

@ -77,13 +77,13 @@ impl RsaRef {
assert!(to.len() >= self.size());
unsafe {
let len = try!(cvt_n(ffi::RSA_private_decrypt(
let len = cvt_n(ffi::RSA_private_decrypt(
from.len() as c_int,
from.as_ptr(),
to.as_mut_ptr(),
self.as_ptr(),
padding.0,
)));
))?;
Ok(len as usize)
}
}
@ -105,13 +105,13 @@ impl RsaRef {
assert!(to.len() >= self.size());
unsafe {
let len = try!(cvt_n(ffi::RSA_private_encrypt(
let len = cvt_n(ffi::RSA_private_encrypt(
from.len() as c_int,
from.as_ptr(),
to.as_mut_ptr(),
self.as_ptr(),
padding.0,
)));
))?;
Ok(len as usize)
}
}
@ -131,13 +131,13 @@ impl RsaRef {
assert!(to.len() >= self.size());
unsafe {
let len = try!(cvt_n(ffi::RSA_public_decrypt(
let len = cvt_n(ffi::RSA_public_decrypt(
from.len() as c_int,
from.as_ptr(),
to.as_mut_ptr(),
self.as_ptr(),
padding.0,
)));
))?;
Ok(len as usize)
}
}
@ -157,13 +157,13 @@ impl RsaRef {
assert!(to.len() >= self.size());
unsafe {
let len = try!(cvt_n(ffi::RSA_public_encrypt(
let len = cvt_n(ffi::RSA_public_encrypt(
from.len() as c_int,
from.as_ptr(),
to.as_mut_ptr(),
self.as_ptr(),
padding.0,
)));
))?;
Ok(len as usize)
}
}
@ -229,13 +229,13 @@ impl Rsa {
/// the supplied load and save methods for DER formatted keys.
pub fn from_public_components(n: BigNum, e: BigNum) -> Result<Rsa, ErrorStack> {
unsafe {
let rsa = Rsa(try!(cvt_p(ffi::RSA_new())));
try!(cvt(compat::set_key(
let rsa = Rsa(cvt_p(ffi::RSA_new())?);
cvt(compat::set_key(
rsa.0,
n.as_ptr(),
e.as_ptr(),
ptr::null_mut(),
)));
))?;
mem::forget((n, e));
Ok(rsa)
}
@ -252,19 +252,19 @@ impl Rsa {
qi: BigNum,
) -> Result<Rsa, ErrorStack> {
unsafe {
let rsa = Rsa(try!(cvt_p(ffi::RSA_new())));
try!(cvt(
let rsa = Rsa(cvt_p(ffi::RSA_new())?);
cvt(
compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr()),
));
)?;
mem::forget((n, e, d));
try!(cvt(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr())));
cvt(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr()))?;
mem::forget((p, q));
try!(cvt(compat::set_crt_params(
cvt(compat::set_crt_params(
rsa.0,
dp.as_ptr(),
dq.as_ptr(),
qi.as_ptr(),
)));
))?;
mem::forget((dp, dq, qi));
Ok(rsa)
}
@ -276,14 +276,14 @@ impl Rsa {
pub fn generate(bits: u32) -> Result<Rsa, ErrorStack> {
ffi::init();
unsafe {
let rsa = Rsa(try!(cvt_p(ffi::RSA_new())));
let e = try!(BigNum::from_u32(ffi::RSA_F4 as u32));
try!(cvt(ffi::RSA_generate_key_ex(
let rsa = Rsa(cvt_p(ffi::RSA_new())?);
let e = BigNum::from_u32(ffi::RSA_F4 as u32)?;
cvt(ffi::RSA_generate_key_ex(
rsa.0,
bits as c_int,
e.as_ptr(),
ptr::null_mut(),
)));
))?;
Ok(rsa)
}
}
@ -308,16 +308,16 @@ impl Rsa {
{
ffi::init();
let mut cb = CallbackState::new(pass_cb);
let mem_bio = try!(MemBioSlice::new(buf));
let mem_bio = MemBioSlice::new(buf)?;
unsafe {
let cb_ptr = &mut cb as *mut _ as *mut c_void;
let rsa = try!(cvt_p(ffi::PEM_read_bio_RSAPrivateKey(
let rsa = cvt_p(ffi::PEM_read_bio_RSAPrivateKey(
mem_bio.as_ptr(),
ptr::null_mut(),
Some(invoke_passwd_cb_old::<F>),
cb_ptr,
)));
))?;
Ok(Rsa(rsa))
}
}

View File

@ -1,4 +1,52 @@
//! The SHA family of hashes.
//!
//! SHA, or Secure Hash Algorithms, are a family of cryptographic hashing algorithms published by
//! the National Institute of Standards and Technology (NIST). Hash algorithms such as those in
//! the SHA family are used to map data of an arbitrary size to a fixed-size string of bytes.
//! As cryptographic hashing algorithms, these mappings have the property of being irreversable.
//! This property makes hash algorithms like these excellent for uses such as verifying the
//! contents of a file- if you know the hash you expect beforehand, then you can verify that the
//! data you have is correct if it hashes to the same value.
//!
//! # Examples
//!
//! When dealing with data that becomes available in chunks, such as while buffering data from IO,
//! you can create a hasher that you can repeatedly update to add bytes to.
//!
//! ```rust
//! extern crate openssl;
//! extern crate hex;
//!
//! use openssl::sha;
//! use hex::ToHex;
//!
//! fn main() {
//! let mut hasher = sha::Sha256::new();
//!
//! hasher.update(b"Hello, ");
//! hasher.update(b"world");
//!
//! let hash = hasher.finish();
//! println!("Hashed \"Hello, world\" to {}", hash.to_hex());
//! }
//! ```
//!
//! On the other hand, if you already have access to all of the data you woud like to hash, you
//! may prefer to use the slightly simpler method of simply calling the hash function corresponding
//! to the algorithm you want to use.
//!
//! ```rust
//! extern crate openssl;
//! extern crate hex;
//!
//! use openssl::sha::sha256;
//! use hex::ToHex;
//!
//! fn main() {
//! let hash = sha256(b"your data or message");
//! println!("Hash = {}", hash.to_hex());
//! }
//! ```
use libc::c_void;
use ffi;
use std::mem;

View File

@ -97,7 +97,7 @@ impl<'a> Signer<'a> {
unsafe {
ffi::init();
let ctx = try!(cvt_p(EVP_MD_CTX_new()));
let ctx = cvt_p(EVP_MD_CTX_new())?;
let mut pctx: *mut ffi::EVP_PKEY_CTX = ptr::null_mut();
let r = ffi::EVP_DigestSignInit(
ctx,
@ -142,17 +142,17 @@ impl<'a> Signer<'a> {
pub fn finish(&self) -> Result<Vec<u8>, ErrorStack> {
unsafe {
let mut len = 0;
try!(cvt(ffi::EVP_DigestSignFinal(
cvt(ffi::EVP_DigestSignFinal(
self.md_ctx,
ptr::null_mut(),
&mut len,
)));
))?;
let mut buf = vec![0; len];
try!(cvt(ffi::EVP_DigestSignFinal(
cvt(ffi::EVP_DigestSignFinal(
self.md_ctx,
buf.as_mut_ptr() as *mut _,
&mut len,
)));
))?;
// The advertised length is not always equal to the real length for things like DSA
buf.truncate(len);
Ok(buf)
@ -162,7 +162,7 @@ impl<'a> Signer<'a> {
impl<'a> Write for Signer<'a> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
try!(self.update(buf));
self.update(buf)?;
Ok(buf.len())
}
@ -191,7 +191,7 @@ impl<'a> Verifier<'a> {
unsafe {
ffi::init();
let ctx = try!(cvt_p(EVP_MD_CTX_new()));
let ctx = cvt_p(EVP_MD_CTX_new())?;
let mut pctx: *mut ffi::EVP_PKEY_CTX = ptr::null_mut();
let r = ffi::EVP_DigestVerifyInit(
ctx,
@ -251,7 +251,7 @@ impl<'a> Verifier<'a> {
impl<'a> Write for Verifier<'a> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
try!(self.update(buf));
self.update(buf)?;
Ok(buf.len())
}

View File

@ -40,7 +40,7 @@ pub fn new<S: Read + Write>(stream: S) -> Result<(*mut BIO, BioMethod), ErrorSta
});
unsafe {
let bio = try!(cvt_p(BIO_new(method.0.get())));
let bio = cvt_p(BIO_new(method.0.get()))?;
compat::BIO_set_data(bio, Box::into_raw(state) as *mut _);
compat::BIO_set_init(bio, 1);

View File

@ -26,7 +26,7 @@ ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg==
";
fn ctx(method: SslMethod) -> Result<SslContextBuilder, ErrorStack> {
let mut ctx = try!(SslContextBuilder::new(method));
let mut ctx = SslContextBuilder::new(method)?;
let mut opts = ssl::SSL_OP_ALL;
opts &= !ssl::SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
@ -64,16 +64,16 @@ impl SslConnectorBuilder {
///
/// The default configuration is subject to change, and is currently derived from Python.
pub fn new(method: SslMethod) -> Result<SslConnectorBuilder, ErrorStack> {
let mut ctx = try!(ctx(method));
try!(ctx.set_default_verify_paths());
let mut ctx = ctx(method)?;
ctx.set_default_verify_paths()?;
// From https://github.com/python/cpython/blob/a170fa162dc03f0a014373349e548954fff2e567/Lib/ssl.py#L193
try!(ctx.set_cipher_list(
ctx.set_cipher_list(
"TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:\
TLS13-AES-128-GCM-SHA256:\
ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:\
ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:\
!aNULL:!eNULL:!MD5:!3DES"
));
)?;
setup_verify(&mut ctx);
Ok(SslConnectorBuilder(ctx))
@ -113,7 +113,7 @@ impl SslConnector {
where
S: Read + Write,
{
try!(self.configure()).connect(domain, stream)
self.configure()?.connect(domain, stream)
}
/// Initiates a client-side TLS session on a stream without performing hostname verification.
@ -127,7 +127,7 @@ impl SslConnector {
&self, stream: S) -> Result<SslStream<S>, HandshakeError<S>>
where S: Read + Write
{
try!(self.configure())
self.configure()?
.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(stream)
}
@ -158,8 +158,8 @@ impl ConnectConfiguration {
where
S: Read + Write,
{
try!(self.0.set_hostname(domain));
try!(setup_verify_hostname(&mut self.0, domain));
self.0.set_hostname(domain)?;
setup_verify_hostname(&mut self.0, domain)?;
self.0.connect(stream)
}
@ -202,7 +202,7 @@ impl SslAcceptorBuilder {
I: IntoIterator,
I::Item: AsRef<X509Ref>,
{
let builder = try!(SslAcceptorBuilder::mozilla_intermediate_raw(method));
let builder = SslAcceptorBuilder::mozilla_intermediate_raw(method)?;
builder.finish_setup(private_key, certificate, chain)
}
@ -222,17 +222,17 @@ impl SslAcceptorBuilder {
I: IntoIterator,
I::Item: AsRef<X509Ref>,
{
let builder = try!(SslAcceptorBuilder::mozilla_modern_raw(method));
let builder = SslAcceptorBuilder::mozilla_modern_raw(method)?;
builder.finish_setup(private_key, certificate, chain)
}
/// Like `mozilla_intermediate`, but does not load the certificate chain and private key.
pub fn mozilla_intermediate_raw(method: SslMethod) -> Result<SslAcceptorBuilder, ErrorStack> {
let mut ctx = try!(ctx(method));
let dh = try!(Dh::from_pem(DHPARAM_PEM.as_bytes()));
try!(ctx.set_tmp_dh(&dh));
try!(setup_curves(&mut ctx));
try!(ctx.set_cipher_list(
let mut ctx = ctx(method)?;
let dh = Dh::from_pem(DHPARAM_PEM.as_bytes())?;
ctx.set_tmp_dh(&dh)?;
setup_curves(&mut ctx)?;
ctx.set_cipher_list(
"ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\
ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\
ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\
@ -243,20 +243,20 @@ impl SslAcceptorBuilder {
DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:\
EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:\
AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS",
));
)?;
Ok(SslAcceptorBuilder(ctx))
}
/// Like `mozilla_modern`, but does not load the certificate chain and private key.
pub fn mozilla_modern_raw(method: SslMethod) -> Result<SslAcceptorBuilder, ErrorStack> {
let mut ctx = try!(ctx(method));
try!(setup_curves(&mut ctx));
try!(ctx.set_cipher_list(
let mut ctx = ctx(method)?;
setup_curves(&mut ctx)?;
ctx.set_cipher_list(
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\
ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\
ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:\
ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256",
));
)?;
Ok(SslAcceptorBuilder(ctx))
}
@ -270,11 +270,11 @@ impl SslAcceptorBuilder {
I: IntoIterator,
I::Item: AsRef<X509Ref>,
{
try!(self.0.set_private_key(private_key));
try!(self.0.set_certificate(certificate));
try!(self.0.check_private_key());
self.0.set_private_key(private_key)?;
self.0.set_certificate(certificate)?;
self.0.check_private_key()?;
for cert in chain {
try!(self.0.add_extra_chain_cert(cert.as_ref().to_owned()));
self.0.add_extra_chain_cert(cert.as_ref().to_owned())?;
}
Ok(self)
}
@ -300,7 +300,7 @@ fn setup_curves(ctx: &mut SslContextBuilder) -> Result<(), ErrorStack> {
use ec::EcKey;
use nid;
let curve = try!(EcKey::from_curve_name(nid::X9_62_PRIME256V1));
let curve = EcKey::from_curve_name(nid::X9_62_PRIME256V1)?;
ctx.set_tmp_ecdh(&curve)
}
@ -327,7 +327,7 @@ impl SslAcceptor {
where
S: Read + Write,
{
let ssl = try!(Ssl::new(&self.0));
let ssl = Ssl::new(&self.0)?;
ssl.accept(stream)
}
}

View File

@ -28,7 +28,7 @@ pub enum Error {
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(fmt.write_str(self.description()));
fmt.write_str(self.description())?;
if let Some(err) = self.cause() {
write!(fmt, ": {}", err)
} else {
@ -98,14 +98,14 @@ impl<S: Any + fmt::Debug> StdError for HandshakeError<S> {
impl<S: Any + fmt::Debug> fmt::Display for HandshakeError<S> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str(StdError::description(self)));
f.write_str(StdError::description(self))?;
match *self {
HandshakeError::SetupFailure(ref e) => try!(write!(f, ": {}", e)),
HandshakeError::SetupFailure(ref e) => write!(f, ": {}", e)?,
HandshakeError::Failure(ref s) |
HandshakeError::Interrupted(ref s) => {
try!(write!(f, ": {}", s.error()));
write!(f, ": {}", s.error())?;
if let Some(err) = s.ssl().verify_result() {
try!(write!(f, ": {}", err));
write!(f, ": {}", err)?;
}
}
}

View File

@ -343,7 +343,7 @@ impl SslContextBuilder {
pub fn new(method: SslMethod) -> Result<SslContextBuilder, ErrorStack> {
unsafe {
init();
let ctx = try!(cvt_p(ffi::SSL_CTX_new(method.as_ptr())));
let ctx = cvt_p(ffi::SSL_CTX_new(method.as_ptr()))?;
Ok(SslContextBuilder::from_ptr(ctx))
}
@ -416,10 +416,10 @@ impl SslContextBuilder {
pub fn set_verify_cert_store(&mut self, cert_store: X509Store) -> Result<(), ErrorStack> {
unsafe {
let ptr = cert_store.as_ptr();
try!(cvt(
cvt(
ffi::SSL_CTX_set0_verify_cert_store(self.as_ptr(), ptr) as
c_int,
));
)?;
mem::forget(cert_store);
Ok(())
@ -579,10 +579,10 @@ impl SslContextBuilder {
/// `set_certificate` to a trusted root.
pub fn add_extra_chain_cert(&mut self, cert: X509) -> Result<(), ErrorStack> {
unsafe {
try!(cvt(ffi::SSL_CTX_add_extra_chain_cert(
cvt(ffi::SSL_CTX_add_extra_chain_cert(
self.as_ptr(),
cert.as_ptr(),
) as c_int));
) as c_int)?;
mem::forget(cert);
Ok(())
}
@ -652,7 +652,7 @@ impl SslContextBuilder {
/// Set the protocols to be used during Next Protocol Negotiation (the protocols
/// supported by the application).
#[cfg(not(libressl261))]
#[cfg(not(any(libressl261, libressl262)))]
pub fn set_npn_protocols(&mut self, protocols: &[&[u8]]) -> Result<(), ErrorStack> {
// Firstly, convert the list of protocols to a byte-array that can be passed to OpenSSL
// APIs -- a list of length-prefixed strings.
@ -661,11 +661,11 @@ impl SslContextBuilder {
unsafe {
// Attach the protocol list to the OpenSSL context structure,
// so that we can refer to it within the callback.
try!(cvt(ffi::SSL_CTX_set_ex_data(
cvt(ffi::SSL_CTX_set_ex_data(
self.as_ptr(),
*NPN_PROTOS_IDX,
Box::into_raw(protocols) as *mut c_void,
)));
))?;
// Now register the callback that performs the default protocol
// matching based on the client-supported list of protocols that
// has been saved.
@ -712,11 +712,11 @@ impl SslContextBuilder {
// ssl ctx's ex_data so that we can configure a function to free it later. In the
// future, it might make sense to pull this into our internal struct Ssl instead of
// leaning on openssl and using function pointers.
try!(cvt(ffi::SSL_CTX_set_ex_data(
cvt(ffi::SSL_CTX_set_ex_data(
self.as_ptr(),
*ALPN_PROTOS_IDX,
Box::into_raw(protocols) as *mut c_void,
)));
))?;
// Now register the callback that performs the default protocol
// matching based on the client-supported list of protocols that
@ -859,7 +859,7 @@ impl SslContext {
{
unsafe {
ffi::init();
let idx = try!(cvt_n(compat::get_new_idx(free_data_box::<T>)));
let idx = cvt_n(compat::get_new_idx(free_data_box::<T>))?;
Ok(Index::from_raw(idx))
}
}
@ -1088,7 +1088,7 @@ impl Ssl {
{
unsafe {
ffi::init();
let idx = try!(cvt_n(compat::get_new_ssl_idx(free_data_box::<T>)));
let idx = cvt_n(compat::get_new_ssl_idx(free_data_box::<T>))?;
Ok(Index::from_raw(idx))
}
}
@ -1311,7 +1311,7 @@ impl SslRef {
///
/// The protocol's name is returned is an opaque sequence of bytes. It is up to the client
/// to interpret it.
#[cfg(not(libressl261))]
#[cfg(not(any(libressl261, libressl262)))]
pub fn selected_npn_protocol(&self) -> Option<&[u8]> {
unsafe {
let mut data: *const c_uchar = ptr::null();
@ -1484,11 +1484,11 @@ impl SslRef {
pub fn set_ocsp_status(&mut self, response: &[u8]) -> Result<(), ErrorStack> {
unsafe {
assert!(response.len() <= c_int::max_value() as usize);
let p = try!(cvt_p(ffi::CRYPTO_malloc(
let p = cvt_p(ffi::CRYPTO_malloc(
response.len() as _,
concat!(file!(), "\0").as_ptr() as *const _,
line!() as c_int,
)));
))?;
ptr::copy_nonoverlapping(response.as_ptr(), p as *mut u8, response.len());
cvt(ffi::SSL_set_tlsext_status_ocsp_resp(
self.as_ptr(),
@ -1540,7 +1540,7 @@ impl fmt::Debug for Ssl {
impl Ssl {
pub fn new(ctx: &SslContext) -> Result<Ssl, ErrorStack> {
unsafe {
let ssl = try!(cvt_p(ffi::SSL_new(ctx.as_ptr())));
let ssl = cvt_p(ffi::SSL_new(ctx.as_ptr()))?;
Ok(Ssl::from_ptr(ssl))
}
}

View File

@ -503,7 +503,7 @@ fn test_connect_with_unilateral_alpn() {
/// Tests that connecting with the client using NPN, but the server not does not
/// break the existing connection behavior.
#[test]
#[cfg(not(libressl261))]
#[cfg(not(any(libressl261, libressl262)))]
fn test_connect_with_unilateral_npn() {
let (_s, stream) = Server::new();
let mut ctx = SslContext::builder(SslMethod::tls()).unwrap();
@ -616,7 +616,7 @@ fn test_connect_with_npn_successful_single_match() {
/// Tests that when the `SslStream` is created as a server stream, the protocols
/// are correctly advertised to the client.
#[test]
#[cfg(not(libressl261))]
#[cfg(not(any(libressl261, libressl262)))]
fn test_npn_server_advertise_multiple() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let localhost = listener.local_addr().unwrap();
@ -1241,7 +1241,7 @@ fn tmp_dh_callback() {
}
#[test]
#[cfg(any(all(feature = "v101", ossl101, not(libressl261)), all(feature = "v102", ossl102)))]
#[cfg(any(all(feature = "v101", ossl101, not(any(libressl261, libressl262))), all(feature = "v102", ossl102)))]
fn tmp_ecdh_callback() {
use ec::EcKey;
use nid;
@ -1308,7 +1308,7 @@ fn tmp_dh_callback_ssl() {
}
#[test]
#[cfg(any(all(feature = "v101", ossl101, not(libressl261)), all(feature = "v102", ossl102)))]
#[cfg(any(all(feature = "v101", ossl101, not(any(libressl261, libressl262))), all(feature = "v102", ossl102)))]
fn tmp_ecdh_callback_ssl() {
use ec::EcKey;
use nid;

View File

@ -37,7 +37,7 @@ impl<T: Stackable> Stack<T> {
pub fn new() -> Result<Stack<T>, ErrorStack> {
unsafe {
ffi::init();
let ptr = try!(cvt_p(OPENSSL_sk_new_null()));
let ptr = cvt_p(OPENSSL_sk_new_null())?;
Ok(Stack(ptr as *mut _))
}
}
@ -218,9 +218,9 @@ impl<T: Stackable> StackRef<T> {
/// Pushes a value onto the top of the stack.
pub fn push(&mut self, data: T) -> Result<(), ErrorStack> {
unsafe {
try!(cvt(
cvt(
OPENSSL_sk_push(self.as_stack(), data.as_ptr() as *mut _),
));
)?;
mem::forget(data);
Ok(())
}

View File

@ -173,7 +173,7 @@ impl Crypter {
ffi::init();
unsafe {
let ctx = try!(cvt_p(ffi::EVP_CIPHER_CTX_new()));
let ctx = cvt_p(ffi::EVP_CIPHER_CTX_new())?;
let crypter = Crypter {
ctx: ctx,
block_size: t.block_size(),
@ -184,46 +184,46 @@ impl Crypter {
Mode::Decrypt => 0,
};
try!(cvt(ffi::EVP_CipherInit_ex(
cvt(ffi::EVP_CipherInit_ex(
crypter.ctx,
t.as_ptr(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
mode,
)));
))?;
assert!(key.len() <= c_int::max_value() as usize);
try!(cvt(ffi::EVP_CIPHER_CTX_set_key_length(
cvt(ffi::EVP_CIPHER_CTX_set_key_length(
crypter.ctx,
key.len() as c_int,
)));
))?;
let key = key.as_ptr() as *mut _;
let iv = match (iv, t.iv_len()) {
(Some(iv), Some(len)) => {
if iv.len() != len {
assert!(iv.len() <= c_int::max_value() as usize);
try!(cvt(ffi::EVP_CIPHER_CTX_ctrl(
cvt(ffi::EVP_CIPHER_CTX_ctrl(
crypter.ctx,
ffi::EVP_CTRL_GCM_SET_IVLEN,
iv.len() as c_int,
ptr::null_mut(),
)));
))?;
}
iv.as_ptr() as *mut _
}
(Some(_), None) | (None, None) => ptr::null_mut(),
(None, Some(_)) => panic!("an IV is required for this cipher"),
};
try!(cvt(ffi::EVP_CipherInit_ex(
cvt(ffi::EVP_CipherInit_ex(
crypter.ctx,
ptr::null(),
ptr::null_mut(),
key,
iv,
mode,
)));
))?;
Ok(crypter)
}
@ -292,13 +292,13 @@ impl Crypter {
let mut outl = output.len() as c_int;
let inl = input.len() as c_int;
try!(cvt(ffi::EVP_CipherUpdate(
cvt(ffi::EVP_CipherUpdate(
self.ctx,
output.as_mut_ptr(),
&mut outl,
input.as_ptr(),
inl,
)));
))?;
Ok(outl as usize)
}
@ -319,11 +319,11 @@ impl Crypter {
assert!(output.len() >= self.block_size);
let mut outl = cmp::min(output.len(), c_int::max_value() as usize) as c_int;
try!(cvt(ffi::EVP_CipherFinal(
cvt(ffi::EVP_CipherFinal(
self.ctx,
output.as_mut_ptr(),
&mut outl,
)));
))?;
Ok(outl as usize)
}
@ -387,10 +387,10 @@ fn cipher(
iv: Option<&[u8]>,
data: &[u8],
) -> Result<Vec<u8>, ErrorStack> {
let mut c = try!(Crypter::new(t, mode, key, iv));
let mut c = Crypter::new(t, mode, key, iv)?;
let mut out = vec![0; data.len() + t.block_size()];
let count = try!(c.update(data, &mut out));
let rest = try!(c.finalize(&mut out[count..]));
let count = c.update(data, &mut out)?;
let rest = c.finalize(&mut out[count..])?;
out.truncate(count + rest);
Ok(out)
}
@ -411,12 +411,12 @@ pub fn encrypt_aead(
data: &[u8],
tag: &mut [u8],
) -> Result<Vec<u8>, ErrorStack> {
let mut c = try!(Crypter::new(t, Mode::Encrypt, key, iv));
let mut c = Crypter::new(t, Mode::Encrypt, key, iv)?;
let mut out = vec![0; data.len() + t.block_size()];
try!(c.aad_update(aad));
let count = try!(c.update(data, &mut out));
let rest = try!(c.finalize(&mut out[count..]));
try!(c.get_tag(tag));
c.aad_update(aad)?;
let count = c.update(data, &mut out)?;
let rest = c.finalize(&mut out[count..])?;
c.get_tag(tag)?;
out.truncate(count + rest);
Ok(out)
}
@ -433,12 +433,12 @@ pub fn decrypt_aead(
data: &[u8],
tag: &[u8],
) -> Result<Vec<u8>, ErrorStack> {
let mut c = try!(Crypter::new(t, Mode::Decrypt, key, iv));
let mut c = Crypter::new(t, Mode::Decrypt, key, iv)?;
let mut out = vec![0; data.len() + t.block_size()];
try!(c.aad_update(aad));
let count = try!(c.update(data, &mut out));
try!(c.set_tag(tag));
let rest = try!(c.finalize(&mut out[count..]));
c.aad_update(aad)?;
let count = c.update(data, &mut out)?;
c.set_tag(tag)?;
let rest = c.finalize(&mut out[count..])?;
out.truncate(count + rest);
Ok(out)
}

View File

@ -100,7 +100,7 @@ impl X509StoreContextRef {
/// Returns a reference to the `Ssl` associated with this context.
pub fn ssl(&self) -> Result<Option<&SslRef>, ErrorStack> {
unsafe {
let idx = try!(cvt_n(ffi::SSL_get_ex_data_X509_STORE_CTX_idx()));
let idx = cvt_n(ffi::SSL_get_ex_data_X509_STORE_CTX_idx())?;
let ssl = ffi::X509_STORE_CTX_get_ex_data(self.as_ptr(), idx);
if ssl.is_null() {
Ok(None)
@ -221,59 +221,59 @@ impl X509Generator {
/// Sets the certificate public-key, then self-sign and return it
#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")]
pub fn sign(&self, p_key: &PKeyRef) -> Result<X509, ErrorStack> {
let mut builder = try!(X509::builder());
try!(builder.set_version(2));
let mut builder = X509::builder()?;
builder.set_version(2)?;
let mut serial = try!(BigNum::new());
try!(serial.rand(128, MSB_MAYBE_ZERO, false));
let serial = try!(serial.to_asn1_integer());
try!(builder.set_serial_number(&serial));
let mut serial = BigNum::new()?;
serial.rand(128, MSB_MAYBE_ZERO, false)?;
let serial = serial.to_asn1_integer()?;
builder.set_serial_number(&serial)?;
let not_before = try!(Asn1Time::days_from_now(0));
try!(builder.set_not_before(&not_before));
let not_after = try!(Asn1Time::days_from_now(self.days));
try!(builder.set_not_after(&not_after));
let not_before = Asn1Time::days_from_now(0)?;
builder.set_not_before(&not_before)?;
let not_after = Asn1Time::days_from_now(self.days)?;
builder.set_not_after(&not_after)?;
try!(builder.set_pubkey(p_key));
builder.set_pubkey(p_key)?;
let mut name = try!(X509Name::builder());
let mut name = X509Name::builder()?;
if self.names.is_empty() {
try!(name.append_entry_by_nid(nid::COMMONNAME, "rust-openssl"));
name.append_entry_by_nid(nid::COMMONNAME, "rust-openssl")?;
} else {
for &(ref key, ref value) in &self.names {
try!(name.append_entry_by_text(key, value));
name.append_entry_by_text(key, value)?;
}
}
let name = name.build();
try!(builder.set_subject_name(&name));
try!(builder.set_issuer_name(&name));
builder.set_subject_name(&name)?;
builder.set_issuer_name(&name)?;
for (exttype, ext) in self.extensions.iter() {
let extension = match exttype.get_nid() {
Some(nid) => {
let ctx = builder.x509v3_context(None, None);
try!(X509Extension::new_nid(
X509Extension::new_nid(
None,
Some(&ctx),
nid,
&ext.to_string(),
))
)?
}
None => {
let ctx = builder.x509v3_context(None, None);
try!(X509Extension::new(
X509Extension::new(
None,
Some(&ctx),
&exttype.get_name().unwrap(),
&ext.to_string(),
))
)?
}
};
try!(builder.append_extension(extension));
builder.append_extension(extension)?;
}
try!(builder.sign(p_key, self.hash_type));
builder.sign(p_key, self.hash_type)?;
Ok(builder.build())
}
@ -286,24 +286,24 @@ impl X509Generator {
};
unsafe {
let req = try!(cvt_p(ffi::X509_to_X509_REQ(
let req = cvt_p(ffi::X509_to_X509_REQ(
cert.as_ptr(),
ptr::null_mut(),
ptr::null(),
)));
))?;
let req = X509Req::from_ptr(req);
let exts = compat::X509_get0_extensions(cert.as_ptr());
if exts != ptr::null_mut() {
try!(cvt(
cvt(
ffi::X509_REQ_add_extensions(req.as_ptr(), exts as *mut _),
));
)?;
}
let hash_fn = self.hash_type.as_ptr();
try!(cvt(
cvt(
ffi::X509_REQ_sign(req.as_ptr(), p_key.as_ptr(), hash_fn),
));
)?;
Ok(req)
}
@ -429,9 +429,9 @@ impl X509Builder {
/// Adds an X509 extension value to the certificate.
pub fn append_extension(&mut self, extension: X509Extension) -> Result<(), ErrorStack> {
unsafe {
try!(cvt(
cvt(
ffi::X509_add_ext(self.0.as_ptr(), extension.as_ptr(), -1),
));
)?;
mem::forget(extension);
Ok(())
}
@ -483,7 +483,7 @@ impl X509Ref {
pub fn public_key(&self) -> Result<PKey, ErrorStack> {
unsafe {
let pkey = try!(cvt_p(ffi::X509_get_pubkey(self.as_ptr())));
let pkey = cvt_p(ffi::X509_get_pubkey(self.as_ptr()))?;
Ok(PKey::from_ptr(pkey))
}
}
@ -494,12 +494,12 @@ impl X509Ref {
let evp = hash_type.as_ptr();
let mut len = ffi::EVP_MAX_MD_SIZE;
let mut buf = vec![0u8; len as usize];
try!(cvt(ffi::X509_digest(
cvt(ffi::X509_digest(
self.as_ptr(),
evp,
buf.as_mut_ptr() as *mut _,
&mut len,
)));
))?;
buf.truncate(len as usize);
Ok(buf)
}
@ -588,7 +588,7 @@ impl X509 {
pub fn stack_from_pem(pem: &[u8]) -> Result<Vec<X509>, ErrorStack> {
unsafe {
ffi::init();
let bio = try!(MemBioSlice::new(pem));
let bio = MemBioSlice::new(pem)?;
let mut certs = vec![];
loop {
@ -934,14 +934,14 @@ impl X509Req {
/// Reads CSR from PEM
pub fn from_pem(buf: &[u8]) -> Result<X509Req, ErrorStack> {
let mem_bio = try!(MemBioSlice::new(buf));
let mem_bio = MemBioSlice::new(buf)?;
unsafe {
let handle = try!(cvt_p(ffi::PEM_read_bio_X509_REQ(
let handle = cvt_p(ffi::PEM_read_bio_X509_REQ(
mem_bio.as_ptr(),
ptr::null_mut(),
None,
ptr::null_mut(),
)));
))?;
Ok(X509Req::from_ptr(handle))
}
}

View File

@ -42,7 +42,7 @@ fn main() {
}
let has_cms_h = if let Ok(version) = env::var("DEP_OPENSSL_LIBRESSL_VERSION") {
version != "261"
version != "261" && version != "262"
} else {
true
};