From 6b1016c86e72d26d15584789456bd317bee92bca Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 7 Aug 2016 22:56:44 -0700 Subject: [PATCH] Add PKey::from_rsa --- openssl-sys/src/lib.rs | 2 ++ openssl/src/crypto/pkey.rs | 14 +++++++++----- openssl/src/x509/mod.rs | 3 +-- openssl/src/x509/tests.rs | 3 +-- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 6966bb8f..58b78d9f 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -284,6 +284,7 @@ pub const BIO_FLAGS_SHOULD_RETRY: c_int = 0x08; pub const CRYPTO_LOCK: c_int = 1; pub const EVP_MAX_MD_SIZE: c_uint = 64; +pub const EVP_PKEY_RSA: c_int = NID_rsaEncryption; pub const MBSTRING_ASC: c_int = MBSTRING_FLAG | 1; pub const MBSTRING_BMP: c_int = MBSTRING_FLAG | 2; @@ -291,6 +292,7 @@ pub const MBSTRING_FLAG: c_int = 0x1000; pub const MBSTRING_UNIV: c_int = MBSTRING_FLAG | 4; pub const MBSTRING_UTF8: c_int = MBSTRING_FLAG; +pub const NID_rsaEncryption: c_int = 6; pub const NID_ext_key_usage: c_int = 126; pub const NID_key_usage: c_int = 83; diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs index 501ffa37..607d4986 100644 --- a/openssl/src/crypto/pkey.rs +++ b/openssl/src/crypto/pkey.rs @@ -1,8 +1,9 @@ use libc::{c_void, c_char}; use std::ptr; -use bio::{MemBio, MemBioSlice}; - +use std::mem; use ffi; + +use bio::{MemBio, MemBioSlice}; use crypto::rsa::RSA; use error::ErrorStack; use crypto::util::{CallbackState, invoke_passwd_cb}; @@ -14,11 +15,14 @@ unsafe impl Sync for PKey {} /// Represents a public key, optionally with a private key attached. impl PKey { - pub fn new() -> Result { - ffi::init(); + /// Create a new `PKey` containing an RSA key. + pub fn from_rsa(rsa: RSA) -> Result { unsafe { let evp = try_ssl_null!(ffi::EVP_PKEY_new()); - Ok(PKey::from_handle(evp)) + let pkey = PKey(evp); + try_ssl!(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_RSA, rsa.as_ptr() as *mut _)); + mem::forget(rsa); + Ok(pkey) } } diff --git a/openssl/src/x509/mod.rs b/openssl/src/x509/mod.rs index 1bce71c6..10537ea2 100644 --- a/openssl/src/x509/mod.rs +++ b/openssl/src/x509/mod.rs @@ -118,8 +118,7 @@ impl X509StoreContext { /// use openssl::x509::extension::{Extension, KeyUsageOption}; /// /// let rsa = RSA::generate(2048).unwrap(); -/// let mut pkey = PKey::new().unwrap(); -/// pkey.set_rsa(&rsa).unwrap(); +/// let pkey = PKey::from_rsa(rsa).unwrap(); /// /// let gen = X509Generator::new() /// .set_valid_period(365*2) diff --git a/openssl/src/x509/tests.rs b/openssl/src/x509/tests.rs index f701736a..da1523af 100644 --- a/openssl/src/x509/tests.rs +++ b/openssl/src/x509/tests.rs @@ -26,8 +26,7 @@ fn get_generator() -> X509Generator { fn pkey() -> PKey { let rsa = RSA::generate(2048).unwrap(); - let mut pkey = PKey::new().unwrap(); - pkey.set_rsa(&rsa).unwrap(); + let mut pkey = PKey::from_rsa(rsa).unwrap(); pkey }