Skip to content

Commit

Permalink
Merge pull request sfackler#389 from cmsd2/master
Browse files Browse the repository at this point in the history
expose rsa from raw private key and rsa sign and verify
  • Loading branch information
sfackler committed May 6, 2016
2 parents 6deb9c7 + f82a1c4 commit dce59a6
Show file tree
Hide file tree
Showing 5 changed files with 241 additions and 19 deletions.
6 changes: 6 additions & 0 deletions openssl-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,12 @@ extern "C" {
callback: Option<PasswordCallback>,
user_data: *mut c_void) -> c_int;
pub fn PEM_write_bio_PUBKEY(bp: *mut BIO, x: *mut EVP_PKEY) -> c_int;
pub fn PEM_write_bio_RSAPrivateKey(bp: *mut BIO, rsa: *mut RSA, cipher: *const EVP_CIPHER,
kstr: *mut c_char, klen: c_int,
callback: Option<PasswordCallback>,
user_data: *mut c_void) -> c_int;
pub fn PEM_write_bio_RSAPublicKey(bp: *mut BIO, rsa: *mut RSA) -> c_int;
pub fn PEM_write_bio_RSA_PUBKEY(bp: *mut BIO, rsa: *mut RSA) -> c_int;
pub fn PEM_write_bio_X509(bio: *mut BIO, x509: *mut X509) -> c_int;
pub fn PEM_write_bio_X509_REQ(bio: *mut BIO, x509: *mut X509_REQ) -> c_int;

Expand Down
160 changes: 159 additions & 1 deletion openssl/src/crypto/rsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ use ffi;
use std::fmt;
use ssl::error::{SslError, StreamError};
use std::ptr;
use std::io::{self, Read};
use std::io::{self, Read, Write};

use bn::BigNum;
use bio::MemBio;
use nid::Nid;

pub struct RSA(*mut ffi::RSA);

Expand All @@ -28,6 +29,21 @@ impl RSA {
Ok(RSA(rsa))
}
}

pub fn from_private_components(n: BigNum, e: BigNum, d: BigNum, p: BigNum, q: BigNum, dp: BigNum, dq: BigNum, qi: BigNum) -> Result<RSA, SslError> {
unsafe {
let rsa = try_ssl_null!(ffi::RSA_new());
(*rsa).n = n.into_raw();
(*rsa).e = e.into_raw();
(*rsa).d = d.into_raw();
(*rsa).p = p.into_raw();
(*rsa).q = q.into_raw();
(*rsa).dmp1 = dp.into_raw();
(*rsa).dmq1 = dq.into_raw();
(*rsa).iqmp = qi.into_raw();
Ok(RSA(rsa))
}
}

/// the caller should assert that the rsa pointer is valid.
pub unsafe fn from_raw(rsa: *mut ffi::RSA) -> RSA {
Expand All @@ -49,6 +65,25 @@ impl RSA {
Ok(RSA(rsa))
}
}

/// Writes an RSA private key as unencrypted PEM formatted data
pub fn private_key_to_pem<W>(&self, writer: &mut W) -> Result<(), SslError>
where W: Write
{
let mut mem_bio = try!(MemBio::new());

let result = unsafe {
ffi::PEM_write_bio_RSAPrivateKey(mem_bio.get_handle(), self.0, ptr::null(), ptr::null_mut(), 0, None, ptr::null_mut())
};

if result == 1 {
try!(io::copy(&mut mem_bio, writer).map_err(StreamError));

Ok(())
} else {
Err(SslError::OpenSslErrors(vec![]))
}
}

/// Reads an RSA public key from PEM formatted data.
pub fn public_key_from_pem<R>(reader: &mut R) -> Result<RSA, SslError>
Expand All @@ -65,6 +100,60 @@ impl RSA {
Ok(RSA(rsa))
}
}

/// Writes an RSA public key as PEM formatted data
pub fn public_key_to_pem<W>(&self, writer: &mut W) -> Result<(), SslError>
where W: Write
{
let mut mem_bio = try!(MemBio::new());

let result = unsafe {
ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.get_handle(), self.0)
};

if result == 1 {
try!(io::copy(&mut mem_bio, writer).map_err(StreamError));

Ok(())
} else {
Err(SslError::OpenSslErrors(vec![]))
}
}

pub fn size(&self) -> Result<u32, SslError> {
if self.has_n() {
unsafe {
Ok(ffi::RSA_size(self.0) as u32)
}
} else {
Err(SslError::OpenSslErrors(vec![]))
}
}

pub fn sign(&self, hash_id: Nid, message: &[u8]) -> Result<Vec<u8>, SslError> {
let k_len = try!(self.size());
let mut sig = vec![0;k_len as usize];
let mut sig_len = k_len;

unsafe {
let result = ffi::RSA_sign(hash_id as i32, message.as_ptr(), message.len() as u32, sig.as_mut_ptr(), &mut sig_len, self.0);
assert!(sig_len == k_len);

if result == 1 {
Ok(sig)
} else {
Err(SslError::OpenSslErrors(vec![]))
}
}
}

pub fn verify(&self, hash_id: Nid, message: &[u8], sig: &[u8]) -> Result<bool, SslError> {
unsafe {
let result = ffi::RSA_verify(hash_id as i32, message.as_ptr(), message.len() as u32, sig.as_ptr(), sig.len() as u32, self.0);

Ok(result == 1)
}
}

pub fn as_ptr(&self) -> *mut ffi::RSA {
self.0
Expand Down Expand Up @@ -119,3 +208,72 @@ impl fmt::Debug for RSA {
write!(f, "RSA")
}
}

#[cfg(test)]
mod test {
use nid;
use std::fs::File;
use std::io::Write;
use super::*;
use crypto::hash::*;

fn signing_input_rs256() -> Vec<u8> {
vec![101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73,
49, 78, 105, 74, 57, 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105,
74, 113, 98, 50, 85, 105, 76, 65, 48, 75, 73, 67, 74, 108, 101, 72,
65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107, 122, 79, 68,
65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76,
121, 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118,
98, 83, 57, 112, 99, 49, 57, 121, 98, 50, 57, 48, 73, 106, 112, 48,
99, 110, 86, 108, 102, 81]
}

fn signature_rs256() -> Vec<u8> {
vec![112, 46, 33, 137, 67, 232, 143, 209, 30, 181, 216, 45, 191, 120, 69,
243, 65, 6, 174, 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125,
131, 101, 109, 66, 10, 253, 60, 150, 238, 221, 115, 162, 102, 62, 81,
102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237, 16, 115, 249, 69,
229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219,
61, 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7,
16, 141, 178, 129, 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31,
190, 127, 249, 217, 46, 10, 231, 111, 36, 242, 91, 51, 187, 230, 244,
74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18, 142, 212, 1,
48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129,
253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239,
177, 139, 93, 163, 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202,
173, 21, 145, 18, 115, 160, 95, 35, 185, 232, 56, 250, 175, 132, 157,
105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195, 212, 14, 96, 69,
34, 165, 68, 200, 242, 122, 122, 45, 184, 6, 99, 209, 108, 247, 202,
234, 86, 222, 64, 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90,
193, 167, 72, 160, 112, 223, 200, 163, 42, 70, 149, 67, 208, 25, 238,
251, 71]
}

#[test]
pub fn test_sign() {
let mut buffer = File::open("test/rsa.pem").unwrap();
let private_key = RSA::private_key_from_pem(&mut buffer).unwrap();

let mut sha = Hasher::new(Type::SHA256);
sha.write_all(&signing_input_rs256()).unwrap();
let digest = sha.finish();

let result = private_key.sign(nid::Nid::SHA256, &digest).unwrap();

assert_eq!(result, signature_rs256());
}

#[test]
pub fn test_verify() {
let mut buffer = File::open("test/rsa.pem.pub").unwrap();
let public_key = RSA::public_key_from_pem(&mut buffer).unwrap();

let mut sha = Hasher::new(Type::SHA256);
sha.write_all(&signing_input_rs256()).unwrap();
let digest = sha.finish();

let result = public_key.verify(nid::Nid::SHA256, &digest, &signature_rs256()).unwrap();

assert!(result);
}
}
58 changes: 40 additions & 18 deletions openssl/src/nid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#[derive(Copy, Clone, Hash, PartialEq, Eq)]
#[repr(usize)]
pub enum Nid {
Undefined,
Undefined, // 0
Rsadsi,
Pkcs,
MD2,
Expand All @@ -12,7 +12,7 @@ pub enum Nid {
RsaEncryption,
RSA_MD2,
RSA_MD5,
PBE_MD2_DES,
PBE_MD2_DES, // 10
X500,
x509,
CN,
Expand All @@ -22,7 +22,7 @@ pub enum Nid {
O,
OU,
RSA,
Pkcs7,
Pkcs7, // 20
Pkcs7_data,
Pkcs7_signedData,
Pkcs7_envelopedData,
Expand All @@ -32,7 +32,7 @@ pub enum Nid {
Pkcs3,
DhKeyAgreement,
DES_ECB,
DES_CFB,
DES_CFB, // 30
DES_CBC,
DES_EDE,
DES_EDE3,
Expand All @@ -42,7 +42,7 @@ pub enum Nid {
RC2_CBC,
RC2_ECB,
RC2_CFB,
RC2_OFB,
RC2_OFB, // 40
SHA,
RSA_SHA,
DES_EDE_CBC,
Expand All @@ -52,7 +52,7 @@ pub enum Nid {
Pkcs9,
Email,
UnstructuredName,
ContentType,
ContentType, // 50
MessageDigest,
SigningTime,
CounterSignature,
Expand All @@ -62,7 +62,7 @@ pub enum Nid {
Netscape,
NetscapeCertExtention,
NetscapeDatatype,
DES_EDE_CFB64,
DES_EDE_CFB64, // 60
DES_EDE3_CFB64,
DES_EDE_OFB64,
DES_EDE3_OFB64,
Expand All @@ -72,7 +72,7 @@ pub enum Nid {
DSA_OLD,
PBE_SHA1_RC2_64,
PBKDF2,
DSA_SHA1_OLD,
DSA_SHA1_OLD, // 70
NetscapeCertType,
NetscapeBaseUrl,
NetscapeRevocationUrl,
Expand All @@ -82,7 +82,7 @@ pub enum Nid {
NetscapeSSLServerName,
NetscapeComment,
NetscapeCertSequence,
DESX_CBC,
DESX_CBC, // 80
ID_CE,
SubjectKeyIdentifier,
KeyUsage,
Expand All @@ -92,7 +92,7 @@ pub enum Nid {
BasicConstraints,
CrlNumber,
CertificatePolicies,
AuthorityKeyIdentifier,
AuthorityKeyIdentifier, // 90
BF_CBC,
BF_ECB,
BF_CFB,
Expand All @@ -102,7 +102,7 @@ pub enum Nid {
RC4_40,
RC2_40_CBC,
G,
S,
S, // 100
I,
/// uniqueIdentifier
UID,
Expand All @@ -113,7 +113,7 @@ pub enum Nid {
D,
CAST5_CBC,
CAST5_ECB,
CAST5_CFB,
CAST5_CFB, // 110
CAST5_OFB,
PbeWithMD5AndCast5CBC,
DSA_SHA1,
Expand All @@ -123,7 +123,7 @@ pub enum Nid {
RIPEMD160,
// 118 missing
RSA_RIPEMD160 = 119,
RC5_CBC,
RC5_CBC, // 120
RC5_ECB,
RC5_CFB,
RC5_OFB,
Expand All @@ -133,7 +133,7 @@ pub enum Nid {
PKIX,
ID_KP,
ServerAuth,
ClientAuth,
ClientAuth, // 130
CodeSigning,
EmailProtection,
TimeStamping,
Expand All @@ -143,7 +143,7 @@ pub enum Nid {
MsSGC,
MsEFS,
NsSGC,
DeltaCRL,
DeltaCRL, // 140
CRLReason,
InvalidityDate,
SXNetID,
Expand All @@ -153,7 +153,7 @@ pub enum Nid {
PBE_SHA1_2DES,
PBE_SHA1_RC2_128,
PBE_SHA1_RC2_40,
KeyBag,
KeyBag, // 150
Pkcs8ShroudedKeyBag,
CertBag,
CrlBag,
Expand All @@ -163,14 +163,36 @@ pub enum Nid {
LocalKeyID,
X509Certificate,
SdsiCertificate,
X509Crl,
X509Crl, // 160
PBES2,
PBMAC1,
HmacWithSha1,
ID_QT_CPS,
ID_QT_UNOTICE,
RC2_64_CBC,
SMIMECaps,
PBE_MD2_RC2_64,
PBE_MD5_RC2_64,
PBE_SHA1_DES,
MicrosoftExtensionRequest,
ExtensionRequest,
Name,
DnQualifier,
IdPe,
IdAd,
AuthorityInfoAccess,
OCSP,
CaIssuers,
OCSPSigning, // 180

// 181 and up are from openssl's obj_mac.h


/// Shown as UID in cert subject
UserId = 458
UserId = 458,


SHA256 = 672,
SHA384,
SHA512,
}
Loading

0 comments on commit dce59a6

Please sign in to comment.