From 1a52649516e5b3924917314ee503523d59ed528b Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sun, 13 Nov 2016 20:46:01 +0000 Subject: [PATCH] More functionality --- openssl-sys/src/lib.rs | 5 +++++ openssl/src/ec_key.rs | 28 ++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/openssl-sys/src/lib.rs b/openssl-sys/src/lib.rs index 11fa46df..230c0148 100644 --- a/openssl-sys/src/lib.rs +++ b/openssl-sys/src/lib.rs @@ -1374,10 +1374,15 @@ extern { #[cfg(not(ossl101))] pub fn DH_get_2048_256() -> *mut DH; + pub fn EC_KEY_new() -> *mut EC_KEY; pub fn EC_KEY_new_by_curve_name(nid: c_int) -> *mut EC_KEY; + pub fn EC_KEY_set_group(key: *mut EC_KEY, group: *const EC_GROUP) -> c_int; pub fn EC_KEY_get0_group(key: *const EC_KEY) -> *const EC_GROUP; + pub fn EC_KEY_set_public_key(key: *mut EC_KEY, key: *const EC_POINT) -> c_int; pub fn EC_KEY_get0_public_key(key: *const EC_KEY) -> *const EC_POINT; + pub fn EC_KEY_set_private_key(key: *mut EC_KEY, key: *const BIGNUM) -> c_int; pub fn EC_KEY_get0_private_key(key: *const EC_KEY) -> *const BIGNUM; + pub fn EC_KEY_generate_key(key: *mut EC_KEY) -> c_int; pub fn EC_KEY_free(key: *mut EC_KEY); pub fn EC_GFp_simple_method() -> *const EC_METHOD; diff --git a/openssl/src/ec_key.rs b/openssl/src/ec_key.rs index 22082b42..e7e92d7a 100644 --- a/openssl/src/ec_key.rs +++ b/openssl/src/ec_key.rs @@ -96,8 +96,11 @@ impl EcKeyRef { pub fn public_key(&self) -> Option<&EcPointRef> { unsafe { let ptr = ffi::EC_KEY_get0_public_key(self.as_ptr()); - assert!(!ptr.is_null()); - EcPointRef::from_ptr(ptr as *mut _) + if ptr.is_null() { + None + } else { + Some(EcPointRef::from_ptr(ptr as *mut _)) + } } } @@ -114,6 +117,9 @@ impl EcKeyRef { } impl EcKey { + /// Constructs an `EcKey` corresponding to a known curve. + /// + /// It will not have an associated public or private key. pub fn from_curve_name(nid: Nid) -> Result { unsafe { init(); @@ -121,6 +127,16 @@ impl EcKey { } } + /// Generates a new public/private key pair on the specified curve. + pub fn generate(group: &EcGroupRef) -> Result { + unsafe { + let key = EcKey(try!(cvt_p(ffi::EC_KEY_new()))); + try!(cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr()))); + try!(cvt(ffi::EC_KEY_generate_key(key.as_ptr()))); + Ok(key) + } + } + #[deprecated(since = "0.9.2", note = "use from_curve_name")] pub fn new_by_curve_name(nid: Nid) -> Result { EcKey::from_curve_name(nid) @@ -151,4 +167,12 @@ mod test { group.components_gfp(&mut p, &mut a, &mut b, &mut ctx).unwrap(); EcGroup::from_components_gfp(&p, &a, &b, &mut ctx).unwrap(); } + + #[test] + fn generate() { + let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); + let key = EcKey::generate(&group).unwrap(); + key.public_key().unwrap(); + key.private_key().unwrap(); + } }