aboutsummaryrefslogtreecommitdiff
path: root/openssl/src/crypto
diff options
context:
space:
mode:
Diffstat (limited to 'openssl/src/crypto')
-rw-r--r--openssl/src/crypto/dsa.rs55
-rw-r--r--openssl/src/crypto/hash.rs12
-rw-r--r--openssl/src/crypto/pkcs12.rs5
-rw-r--r--openssl/src/crypto/pkcs5.rs249
-rw-r--r--openssl/src/crypto/pkey.rs55
-rw-r--r--openssl/src/crypto/rand.rs5
-rw-r--r--openssl/src/crypto/rsa.rs263
-rw-r--r--openssl/src/crypto/sign.rs17
-rw-r--r--openssl/src/crypto/symm.rs27
9 files changed, 323 insertions, 365 deletions
diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs
index addaae2f..f9044661 100644
--- a/openssl/src/crypto/dsa.rs
+++ b/openssl/src/crypto/dsa.rs
@@ -4,26 +4,25 @@ use error::ErrorStack;
use std::ptr;
use libc::{c_int, c_char, c_void};
+use {cvt, cvt_p};
use bn::BigNumRef;
use bio::{MemBio, MemBioSlice};
use crypto::util::{CallbackState, invoke_passwd_cb};
-
/// Builder for upfront DSA parameter generation
pub struct DSAParams(*mut ffi::DSA);
impl DSAParams {
pub fn with_size(size: u32) -> Result<DSAParams, ErrorStack> {
unsafe {
- // Wrap it so that if we panic we'll call the dtor
- let dsa = DSAParams(try_ssl_null!(ffi::DSA_new()));
- try_ssl!(ffi::DSA_generate_parameters_ex(dsa.0,
+ let dsa = DSAParams(try!(cvt_p(ffi::DSA_new())));
+ try!(cvt(ffi::DSA_generate_parameters_ex(dsa.0,
size as c_int,
ptr::null(),
0,
ptr::null_mut(),
ptr::null_mut(),
- ptr::null_mut()));
+ ptr::null_mut())));
Ok(dsa)
}
}
@@ -31,7 +30,7 @@ impl DSAParams {
/// Generate a key pair from the initialized parameters
pub fn generate(self) -> Result<DSA, ErrorStack> {
unsafe {
- try_ssl!(ffi::DSA_generate_key(self.0));
+ try!(cvt(ffi::DSA_generate_key(self.0)));
let dsa = DSA(self.0);
::std::mem::forget(self);
Ok(dsa)
@@ -75,13 +74,11 @@ impl DSA {
let mem_bio = try!(MemBioSlice::new(buf));
unsafe {
- let dsa = try_ssl_null!(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(),
- ptr::null_mut(),
- None,
- ptr::null_mut()));
- let dsa = DSA(dsa);
- assert!(dsa.has_private_key());
- Ok(dsa)
+ let dsa = try!(cvt_p(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ None,
+ ptr::null_mut())));
+ Ok(DSA(dsa))
}
}
@@ -99,13 +96,11 @@ impl DSA {
unsafe {
let cb_ptr = &mut cb as *mut _ as *mut c_void;
- let dsa = try_ssl_null!(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(),
- ptr::null_mut(),
- Some(invoke_passwd_cb::<F>),
- cb_ptr));
- let dsa = DSA(dsa);
- assert!(dsa.has_private_key());
- Ok(dsa)
+ let dsa = try!(cvt_p(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ Some(invoke_passwd_cb::<F>),
+ cb_ptr)));
+ Ok(DSA(dsa))
}
}
@@ -116,9 +111,9 @@ impl DSA {
let mem_bio = try!(MemBio::new());
unsafe {
- try_ssl!(ffi::PEM_write_bio_DSAPrivateKey(mem_bio.as_ptr(), self.0,
- ptr::null(), ptr::null_mut(), 0,
- None, ptr::null_mut()))
+ try!(cvt(ffi::PEM_write_bio_DSAPrivateKey(mem_bio.as_ptr(), self.0,
+ ptr::null(), ptr::null_mut(), 0,
+ None, ptr::null_mut())))
};
Ok(mem_bio.get_buf().to_owned())
@@ -131,10 +126,10 @@ impl DSA {
let mem_bio = try!(MemBioSlice::new(buf));
unsafe {
- let dsa = try_ssl_null!(ffi::PEM_read_bio_DSA_PUBKEY(mem_bio.as_ptr(),
- ptr::null_mut(),
- None,
- ptr::null_mut()));
+ let dsa = try!(cvt_p(ffi::PEM_read_bio_DSA_PUBKEY(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ None,
+ ptr::null_mut())));
Ok(DSA(dsa))
}
}
@@ -142,7 +137,9 @@ impl DSA {
/// Writes an DSA public key as PEM formatted data
pub fn public_key_to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
let mem_bio = try!(MemBio::new());
- unsafe { try_ssl!(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.as_ptr(), self.0)) };
+ unsafe {
+ try!(cvt(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.as_ptr(), self.0)));
+ }
Ok(mem_bio.get_buf().to_owned())
}
@@ -239,11 +236,9 @@ impl fmt::Debug for DSA {
#[cfg(test)]
mod test {
- use std::io::Write;
use libc::c_char;
use super::*;
- use crypto::hash::*;
#[test]
pub fn test_generate() {
diff --git a/openssl/src/crypto/hash.rs b/openssl/src/crypto/hash.rs
index 2fa75807..ec265631 100644
--- a/openssl/src/crypto/hash.rs
+++ b/openssl/src/crypto/hash.rs
@@ -1,6 +1,5 @@
use std::io::prelude::*;
use std::io;
-use std::ptr;
use ffi;
#[cfg(ossl110)]
@@ -8,6 +7,7 @@ use ffi::{EVP_MD_CTX_new, EVP_MD_CTX_free};
#[cfg(any(ossl101, ossl102))]
use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free};
+use {cvt, cvt_p};
use error::ErrorStack;
#[derive(Copy, Clone)]
@@ -116,7 +116,7 @@ impl Hasher {
pub fn new(ty: MessageDigest) -> Result<Hasher, ErrorStack> {
ffi::init();
- let ctx = unsafe { try_ssl_null!(EVP_MD_CTX_new()) };
+ let ctx = unsafe { try!(cvt_p(EVP_MD_CTX_new())) };
let mut h = Hasher {
ctx: ctx,
@@ -136,7 +136,7 @@ impl Hasher {
}
Finalized => (),
}
- unsafe { try_ssl!(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _)); }
+ unsafe { try!(cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))); }
self.state = Reset;
Ok(())
}
@@ -147,9 +147,9 @@ impl Hasher {
try!(self.init());
}
unsafe {
- try_ssl!(ffi::EVP_DigestUpdate(self.ctx,
+ try!(cvt(ffi::EVP_DigestUpdate(self.ctx,
data.as_ptr() as *mut _,
- data.len()));
+ data.len())));
}
self.state = Updated;
Ok(())
@@ -164,7 +164,7 @@ impl Hasher {
unsafe {
let mut len = ffi::EVP_MAX_MD_SIZE;
let mut res = vec![0; len as usize];
- try_ssl!(ffi::EVP_DigestFinal_ex(self.ctx, res.as_mut_ptr(), &mut len));
+ try!(cvt(ffi::EVP_DigestFinal_ex(self.ctx, res.as_mut_ptr(), &mut len)));
res.truncate(len as usize);
self.state = Finalized;
Ok(res)
diff --git a/openssl/src/crypto/pkcs12.rs b/openssl/src/crypto/pkcs12.rs
index b028f29d..846b7baf 100644
--- a/openssl/src/crypto/pkcs12.rs
+++ b/openssl/src/crypto/pkcs12.rs
@@ -6,6 +6,7 @@ use std::cmp;
use std::ptr;
use std::ffi::CString;
+use {cvt, cvt_p};
use crypto::pkey::PKey;
use error::ErrorStack;
use x509::X509;
@@ -26,7 +27,7 @@ impl Pkcs12 {
ffi::init();
let mut ptr = der.as_ptr() as *const c_uchar;
let length = cmp::min(der.len(), c_long::max_value() as usize) as c_long;
- let p12 = try_ssl_null!(ffi::d2i_PKCS12(ptr::null_mut(), &mut ptr, length));
+ let p12 = try!(cvt_p(ffi::d2i_PKCS12(ptr::null_mut(), &mut ptr, length)));
Ok(Pkcs12(p12))
}
}
@@ -40,7 +41,7 @@ impl Pkcs12 {
let mut cert = ptr::null_mut();
let mut chain = ptr::null_mut();
- try_ssl!(ffi::PKCS12_parse(self.0, pass.as_ptr(), &mut pkey, &mut cert, &mut chain));
+ try!(cvt(ffi::PKCS12_parse(self.0, pass.as_ptr(), &mut pkey, &mut cert, &mut chain)));
let pkey = PKey::from_ptr(pkey);
let cert = X509::from_ptr(cert);
diff --git a/openssl/src/crypto/pkcs5.rs b/openssl/src/crypto/pkcs5.rs
index 9d348b89..8bcb9b31 100644
--- a/openssl/src/crypto/pkcs5.rs
+++ b/openssl/src/crypto/pkcs5.rs
@@ -2,6 +2,7 @@ use libc::c_int;
use std::ptr;
use ffi;
+use cvt;
use crypto::hash::MessageDigest;
use crypto::symm::Cipher;
use error::ErrorStack;
@@ -9,26 +10,27 @@ use error::ErrorStack;
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct KeyIvPair {
pub key: Vec<u8>,
- pub iv: Vec<u8>,
+ pub iv: Option<Vec<u8>>,
}
/// Derives a key and an IV from various parameters.
///
-/// If specified `salt` must be 8 bytes in length.
+/// If specified, `salt` must be 8 bytes in length.
///
/// If the total key and IV length is less than 16 bytes and MD5 is used then
/// the algorithm is compatible with the key derivation algorithm from PKCS#5
/// v1.5 or PBKDF1 from PKCS#5 v2.0.
///
-/// New applications should not use this and instead use `pbkdf2_hmac_sha1` or
-/// another more modern key derivation algorithm.
-pub fn evp_bytes_to_key_pbkdf1_compatible(cipher: Cipher,
- digest: MessageDigest,
- data: &[u8],
- salt: Option<&[u8]>,
- count: u32)
- -> Result<KeyIvPair, ErrorStack> {
+/// New applications should not use this and instead use
+/// `pkcs5_pbkdf2_hmac_sha1` or another more modern key derivation algorithm.
+pub fn bytes_to_key(cipher: Cipher,
+ digest: MessageDigest,
+ data: &[u8],
+ salt: Option<&[u8]>,
+ count: i32)
+ -> Result<KeyIvPair, ErrorStack> {
unsafe {
+ assert!(data.len() <= c_int::max_value() as usize);
let salt_ptr = match salt {
Some(salt) => {
assert_eq!(salt.len(), ffi::PKCS5_SALT_LEN as usize);
@@ -39,78 +41,58 @@ pub fn evp_bytes_to_key_pbkdf1_compatible(cipher: Cipher,
ffi::init();
+ let mut iv = cipher.iv_len().map(|l| vec![0; l]);
+
let cipher = cipher.as_ptr();
let digest = digest.as_ptr();
- let len = ffi::EVP_BytesToKey(cipher,
- digest,
- salt_ptr,
- data.as_ptr(),
- data.len() as c_int,
- count as c_int,
- ptr::null_mut(),
- ptr::null_mut());
- if len == 0 {
- return Err(ErrorStack::get());
- }
+ let len = try!(cvt(ffi::EVP_BytesToKey(cipher,
+ digest,
+ salt_ptr,
+ ptr::null(),
+ data.len() as c_int,
+ count.into(),
+ ptr::null_mut(),
+ ptr::null_mut())));
let mut key = vec![0; len as usize];
- let mut iv = vec![0; len as usize];
+ let iv_ptr = iv.as_mut().map(|v| v.as_mut_ptr()).unwrap_or(ptr::null_mut());
- try_ssl!(ffi::EVP_BytesToKey(cipher,
+ try!(cvt(ffi::EVP_BytesToKey(cipher,
digest,
salt_ptr,
data.as_ptr(),
data.len() as c_int,
count as c_int,
key.as_mut_ptr(),
- iv.as_mut_ptr()));
+ iv_ptr)));
Ok(KeyIvPair { key: key, iv: iv })
}
}
-/// Derives a key from a password and salt using the PBKDF2-HMAC-SHA1 algorithm.
-pub fn pbkdf2_hmac_sha1(pass: &[u8],
- salt: &[u8],
- iter: usize,
- keylen: usize)
- -> Result<Vec<u8>, ErrorStack> {
- unsafe {
- let mut out = vec![0; keylen];
-
- ffi::init();
-
- try_ssl!(ffi::PKCS5_PBKDF2_HMAC_SHA1(pass.as_ptr() as *const _,
- pass.len() as c_int,
- salt.as_ptr(),
- salt.len() as c_int,
- iter as c_int,
- keylen as c_int,
- out.as_mut_ptr()));
- Ok(out)
- }
-}
-
/// Derives a key from a password and salt using the PBKDF2-HMAC algorithm with a digest function.
pub fn pbkdf2_hmac(pass: &[u8],
salt: &[u8],
iter: usize,
hash: MessageDigest,
- keylen: usize)
- -> Result<Vec<u8>, ErrorStack> {
+ key: &mut [u8])
+ -> Result<(), ErrorStack> {
unsafe {
- let mut out = vec![0; keylen];
+ assert!(pass.len() <= c_int::max_value() as usize);
+ assert!(salt.len() <= c_int::max_value() as usize);
+ assert!(key.len() <= c_int::max_value() as usize);
+
ffi::init();
- try_ssl!(ffi::PKCS5_PBKDF2_HMAC(pass.as_ptr() as *const _,
- pass.len() as c_int,
- salt.as_ptr(),
- salt.len() as c_int,
- iter as c_int,
- hash.as_ptr(),
- keylen as c_int,
- out.as_mut_ptr()));
- Ok(out)
+ cvt(ffi::PKCS5_PBKDF2_HMAC(pass.as_ptr() as *const _,
+ pass.len() as c_int,
+ salt.as_ptr(),
+ salt.len() as c_int,
+ iter as c_int,
+ hash.as_ptr(),
+ key.len() as c_int,
+ key.as_mut_ptr()))
+ .map(|_| ())
}
}
@@ -120,96 +102,67 @@ mod tests {
use crypto::symm::Cipher;
// Test vectors from
- // http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06
- #[test]
- fn test_pbkdf2_hmac_sha1() {
- assert_eq!(super::pbkdf2_hmac_sha1(b"password", b"salt", 1, 20).unwrap(),
- vec![0x0c_u8, 0x60_u8, 0xc8_u8, 0x0f_u8, 0x96_u8, 0x1f_u8, 0x0e_u8, 0x71_u8,
- 0xf3_u8, 0xa9_u8, 0xb5_u8, 0x24_u8, 0xaf_u8, 0x60_u8, 0x12_u8, 0x06_u8,
- 0x2f_u8, 0xe0_u8, 0x37_u8, 0xa6_u8]);
-
- assert_eq!(super::pbkdf2_hmac_sha1(b"password", b"salt", 2, 20).unwrap(),
- vec![0xea_u8, 0x6c_u8, 0x01_u8, 0x4d_u8, 0xc7_u8, 0x2d_u8, 0x6f_u8, 0x8c_u8,
- 0xcd_u8, 0x1e_u8, 0xd9_u8, 0x2a_u8, 0xce_u8, 0x1d_u8, 0x41_u8, 0xf0_u8,
- 0xd8_u8, 0xde_u8, 0x89_u8, 0x57_u8]);
-
- assert_eq!(super::pbkdf2_hmac_sha1(b"password", b"salt", 4096, 20).unwrap(),
- vec![0x4b_u8, 0x00_u8, 0x79_u8, 0x01_u8, 0xb7_u8, 0x65_u8, 0x48_u8, 0x9a_u8,
- 0xbe_u8, 0xad_u8, 0x49_u8, 0xd9_u8, 0x26_u8, 0xf7_u8, 0x21_u8, 0xd0_u8,
- 0x65_u8, 0xa4_u8, 0x29_u8, 0xc1_u8]);
-
- assert_eq!(super::pbkdf2_hmac_sha1(b"password", b"salt", 16777216, 20).unwrap(),
- vec![0xee_u8, 0xfe_u8, 0x3d_u8, 0x61_u8, 0xcd_u8, 0x4d_u8, 0xa4_u8, 0xe4_u8,
- 0xe9_u8, 0x94_u8, 0x5b_u8, 0x3d_u8, 0x6b_u8, 0xa2_u8, 0x15_u8, 0x8c_u8,
- 0x26_u8, 0x34_u8, 0xe9_u8, 0x84_u8]);
-
- assert_eq!(super::pbkdf2_hmac_sha1(b"passwordPASSWORDpassword",
- b"saltSALTsaltSALTsaltSALTsaltSALTsalt",
- 4096,
- 25).unwrap(),
- vec![0x3d_u8, 0x2e_u8, 0xec_u8, 0x4f_u8, 0xe4_u8, 0x1c_u8, 0x84_u8, 0x9b_u8,
- 0x80_u8, 0xc8_u8, 0xd8_u8, 0x36_u8, 0x62_u8, 0xc0_u8, 0xe4_u8, 0x4a_u8,
- 0x8b_u8, 0x29_u8, 0x1a_u8, 0x96_u8, 0x4c_u8, 0xf2_u8, 0xf0_u8, 0x70_u8,
- 0x38_u8]);
-
- assert_eq!(super::pbkdf2_hmac_sha1(b"pass\x00word", b"sa\x00lt", 4096, 16).unwrap(),
- vec![0x56_u8, 0xfa_u8, 0x6a_u8, 0xa7_u8, 0x55_u8, 0x48_u8, 0x09_u8, 0x9d_u8,
- 0xcc_u8, 0x37_u8, 0xd7_u8, 0xf0_u8, 0x34_u8, 0x25_u8, 0xe0_u8, 0xc3_u8]);
- }
-
- // Test vectors from
// https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c
#[test]
- fn test_pbkdf2_hmac_sha256() {
- assert_eq!(super::pbkdf2_hmac(b"passwd", b"salt", 1, MessageDigest::sha256(), 16).unwrap(),
- vec![0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8,
- 0xec_u8, 0x16_u8, 0x91_u8, 0xc2_u8, 0x25_u8, 0x44_u8, 0xb6_u8, 0x05_u8]);
-
- assert_eq!(super::pbkdf2_hmac(b"Password", b"NaCl", 80000, MessageDigest::sha256(), 16).unwrap(),
- vec![0x4d_u8, 0xdc_u8, 0xd8_u8, 0xf6_u8, 0x0b_u8, 0x98_u8, 0xbe_u8, 0x21_u8,
- 0x83_u8, 0x0c_u8, 0xee_u8, 0x5e_u8, 0xf2_u8, 0x27_u8, 0x01_u8, 0xf9_u8]);
+ fn pbkdf2_hmac_sha256() {
+ let mut buf = [0; 16];
+
+ super::pbkdf2_hmac(b"passwd", b"salt", 1, MessageDigest::sha256(), &mut buf).unwrap();
+ assert_eq!(buf,
+ &[0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8,
+ 0xec_u8, 0x16_u8, 0x91_u8, 0xc2_u8, 0x25_u8, 0x44_u8, 0xb6_u8, 0x05_u8][..]);
+
+ super::pbkdf2_hmac(b"Password", b"NaCl", 80000, MessageDigest::sha256(), &mut buf).unwrap();
+ assert_eq!(buf,
+ &[0x4d_u8, 0xdc_u8, 0xd8_u8, 0xf6_u8, 0x0b_u8, 0x98_u8, 0xbe_u8, 0x21_u8,
+ 0x83_u8, 0x0c_u8, 0xee_u8, 0x5e_u8, 0xf2_u8, 0x27_u8, 0x01_u8, 0xf9_u8][..]);
}
// Test vectors from
// https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c
#[test]
- fn test_pbkdf2_hmac_sha512() {
- assert_eq!(super::pbkdf2_hmac(b"password", b"NaCL", 1, MessageDigest::sha512(), 64).unwrap(),
- vec![0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8, 0x4f_u8,
- 0x94_u8, 0x77_u8, 0x1a_u8, 0x75_u8, 0x73_u8, 0x6b_u8, 0xb8_u8, 0x8b_u8,
- 0xd3_u8, 0xc7_u8, 0xb3_u8, 0x82_u8, 0x70_u8, 0xcf_u8, 0xb5_u8, 0x0c_u8,
- 0xb3_u8, 0x90_u8, 0xed_u8, 0x78_u8, 0xb3_u8, 0x05_u8, 0x65_u8, 0x6a_u8,
- 0xf8_u8, 0x14_u8, 0x8e_u8, 0x52_u8, 0x45_u8, 0x2b_u8, 0x22_u8, 0x16_u8,
- 0xb2_u8, 0xb8_u8, 0x09_u8, 0x8b_u8, 0x76_u8, 0x1f_u8, 0xc6_u8, 0x33_u8,
- 0x60_u8, 0x60_u8, 0xa0_u8, 0x9f_u8, 0x76_u8, 0x41_u8, 0x5e_u8, 0x9f_u8,
- 0x71_u8, 0xea_u8, 0x47_u8, 0xf9_u8, 0xe9_u8, 0x06_u8, 0x43_u8, 0x06_u8]);
-
- assert_eq!(super::pbkdf2_hmac(b"pass\0word", b"sa\0lt", 1, MessageDigest::sha512(), 64).unwrap(),
- vec![0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8, 0x67_u8,
- 0x8b_u8, 0xcf_u8, 0xd1_u8, 0x45_u8, 0xf0_u8, 0x9d_u8, 0x83_u8, 0x52_u8,
- 0x2f_u8, 0x93_u8, 0x36_u8, 0x15_u8, 0x60_u8, 0x56_u8, 0x3c_u8, 0x4d_u8,
- 0x0d_u8, 0x63_u8, 0xb8_u8, 0x83_u8, 0x29_u8, 0x87_u8, 0x10_u8, 0x90_u8,
- 0xe7_u8, 0x66_u8, 0x04_u8, 0xa4_u8, 0x9a_u8, 0xf0_u8, 0x8f_u8, 0xe7_u8,
- 0xc9_u8, 0xf5_u8, 0x71_u8, 0x56_u8, 0xc8_u8, 0x79_u8, 0x09_u8, 0x96_u8,
- 0xb2_u8, 0x0f_u8, 0x06_u8, 0xbc_u8, 0x53_u8, 0x5e_u8, 0x5a_u8, 0xb5_u8,
- 0x44_u8, 0x0d_u8, 0xf7_u8, 0xe8_u8, 0x78_u8, 0x29_u8, 0x6f_u8, 0xa7_u8]);
-
- assert_eq!(super::pbkdf2_hmac(b"passwordPASSWORDpassword",
- b"salt\0\0\0",
- 50,
- MessageDigest::sha512(),
- 64).unwrap(),
- vec![0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8, 0x96_u8,
- 0x85_u8, 0x7f_u8, 0xd2_u8, 0xb9_u8, 0xf8_u8, 0xca_u8, 0x28_u8, 0x02_u8,
- 0x3b_u8, 0x30_u8, 0xee_u8, 0x2a_u8, 0x39_u8, 0xf5_u8, 0xad_u8, 0xca_u8,
- 0xc8_u8, 0xc9_u8, 0x37_u8, 0x5f_u8, 0x9b_u8, 0xda_u8, 0x1c_u8, 0xcd_u8,
- 0x1b_u8, 0x6f_u8, 0x0b_u8, 0x2f_u8, 0xc3_u8, 0xad_u8, 0xda_u8, 0x50_u8,
- 0x54_u8, 0x12_u8, 0xe7_u8, 0x9d_u8, 0x89_u8, 0x00_u8, 0x56_u8, 0xc6_u8,
- 0x2e_u8, 0x52_u8, 0x4c_u8, 0x7d_u8, 0x51_u8, 0x15_u8, 0x4b_u8, 0x1a_u8,
- 0x85_u8, 0x34_u8, 0x57_u8, 0x5b_u8, 0xd0_u8, 0x2d_u8, 0xee_u8, 0x39_u8]);
+ fn pbkdf2_hmac_sha512() {
+ let mut buf = [0; 64];
+
+ super::pbkdf2_hmac(b"password", b"NaCL", 1, MessageDigest::sha512(), &mut buf).unwrap();
+ assert_eq!(&buf[..],
+ &[0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8, 0x4f_u8,
+ 0x94_u8, 0x77_u8, 0x1a_u8, 0x75_u8, 0x73_u8, 0x6b_u8, 0xb8_u8, 0x8b_u8,
+ 0xd3_u8, 0xc7_u8, 0xb3_u8, 0x82_u8, 0x70_u8, 0xcf_u8, 0xb5_u8, 0x0c_u8,
+ 0xb3_u8, 0x90_u8, 0xed_u8, 0x78_u8, 0xb3_u8, 0x05_u8, 0x65_u8, 0x6a_u8,
+ 0xf8_u8, 0x14_u8, 0x8e_u8, 0x52_u8, 0x45_u8, 0x2b_u8, 0x22_u8, 0x16_u8,
+ 0xb2_u8, 0xb8_u8, 0x09_u8, 0x8b_u8, 0x76_u8, 0x1f_u8, 0xc6_u8, 0x33_u8,
+ 0x60_u8, 0x60_u8, 0xa0_u8, 0x9f_u8, 0x76_u8, 0x41_u8, 0x5e_u8, 0x9f_u8,
+ 0x71_u8, 0xea_u8, 0x47_u8, 0xf9_u8, 0xe9_u8, 0x06_u8, 0x43_u8, 0x06_u8][..]);
+
+ super::pbkdf2_hmac(b"pass\0word", b"sa\0lt", 1, MessageDigest::sha512(), &mut buf).unwrap();
+ assert_eq!(&buf[..],
+ &[0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8, 0x67_u8,
+ 0x8b_u8, 0xcf_u8, 0xd1_u8, 0x45_u8, 0xf0_u8, 0x9d_u8, 0x83_u8, 0x52_u8,
+ 0x2f_u8, 0x93_u8, 0x36_u8, 0x15_u8, 0x60_u8, 0x56_u8, 0x3c_u8, 0x4d_u8,
+ 0x0d_u8, 0x63_u8, 0xb8_u8, 0x83_u8, 0x29_u8, 0x87_u8, 0x10_u8, 0x90_u8,
+ 0xe7_u8, 0x66_u8, 0x04_u8, 0xa4_u8, 0x9a_u8, 0xf0_u8, 0x8f_u8, 0xe7_u8,
+ 0xc9_u8, 0xf5_u8, 0x71_u8, 0x56_u8, 0xc8_u8, 0x79_u8, 0x09_u8, 0x96_u8,
+ 0xb2_u8, 0x0f_u8, 0x06_u8, 0xbc_u8, 0x53_u8, 0x5e_u8, 0x5a_u8, 0xb5_u8,
+ 0x44_u8, 0x0d_u8, 0xf7_u8, 0xe8_u8, 0x78_u8, 0x29_u8, 0x6f_u8, 0xa7_u8][..]);
+
+ super::pbkdf2_hmac(b"passwordPASSWORDpassword",
+ b"salt\0\0\0",
+ 50,
+ MessageDigest::sha512(),
+ &mut buf).unwrap();
+ assert_eq!(&buf[..],
+ &[0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8, 0x96_u8,
+ 0x85_u8, 0x7f_u8, 0xd2_u8, 0xb9_u8, 0xf8_u8, 0xca_u8, 0x28_u8, 0x02_u8,
+ 0x3b_u8, 0x30_u8, 0xee_u8, 0x2a_u8, 0x39_u8, 0xf5_u8, 0xad_u8, 0xca_u8,
+ 0xc8_u8, 0xc9_u8, 0x37_u8, 0x5f_u8, 0x9b_u8, 0xda_u8, 0x1c_u8, 0xcd_u8,
+ 0x1b_u8, 0x6f_u8, 0x0b_u8, 0x2f_u8, 0xc3_u8, 0xad_u8, 0xda_u8, 0x50_u8,
+ 0x54_u8, 0x12_u8, 0xe7_u8, 0x9d_u8, 0x89_u8, 0x00_u8, 0x56_u8, 0xc6_u8,
+ 0x2e_u8, 0x52_u8, 0x4c_u8, 0x7d_u8, 0x51_u8, 0x15_u8, 0x4b_u8, 0x1a_u8,
+ 0x85_u8, 0x34_u8, 0x57_u8, 0x5b_u8, 0xd0_u8, 0x2d_u8, 0xee_u8, 0x39_u8][..]);
}
#[test]
- fn test_evp_bytes_to_key_pbkdf1_compatible() {
+ fn bytes_to_key() {
let salt = [16_u8, 34_u8, 19_u8, 23_u8, 141_u8, 4_u8, 207_u8, 221_u8];
let data = [143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8, 241_u8, 242_u8, 31_u8,
@@ -224,18 +177,16 @@ mod tests {
98_u8, 245_u8, 246_u8, 238_u8, 177_u8, 229_u8, 161_u8, 183_u8,
224_u8, 174_u8, 3_u8, 6_u8, 244_u8, 236_u8, 255_u8];
let expected_iv = vec![4_u8, 223_u8, 153_u8, 219_u8, 28_u8, 142_u8, 234_u8, 68_u8, 227_u8,
- 69_u8, 98_u8, 107_u8, 208_u8, 14_u8, 236_u8, 60_u8, 0_u8, 0_u8,
- 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8,
- 0_u8, 0_u8, 0_u8];
-
- assert_eq!(super::evp_bytes_to_key_pbkdf1_compatible(Cipher::aes_256_cbc(),
- MessageDigest::sha1(),
- &data,
- Some(&salt),
- 1).unwrap(),
+ 69_u8, 98_u8, 107_u8, 208_u8, 14_u8, 236_u8, 60_u8];
+
+ assert_eq!(super::bytes_to_key(Cipher::aes_256_cbc(),
+ MessageDigest::sha1(),
+ &data,
+ Some(&salt),
+ 1).unwrap(),
super::KeyIvPair {
key: expected_key,
- iv: expected_iv,
+ iv: Some(expected_iv),
});
}
}
diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs
index 67ff7520..1d062cfa 100644
--- a/openssl/src/crypto/pkey.rs
+++ b/openssl/src/crypto/pkey.rs
@@ -3,6 +3,7 @@ use std::ptr;
use std::mem;
use ffi;
+use {cvt, cvt_p};
use bio::{MemBio, MemBioSlice};
use crypto::dsa::DSA;
use crypto::rsa::RSA;
@@ -19,9 +20,9 @@ impl PKey {
/// Create a new `PKey` containing an RSA key.
pub fn from_rsa(rsa: RSA) -> Result<PKey, ErrorStack> {
unsafe {
- let evp = try_ssl_null!(ffi::EVP_PKEY_new());
+ let evp = try!(cvt_p(ffi::EVP_PKEY_new()));
let pkey = PKey(evp);
- try_ssl!(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_RSA, rsa.as_ptr() as *mut _));
+ try!(cvt(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_RSA, rsa.as_ptr() as *mut _)));
mem::forget(rsa);
Ok(pkey)
}
@@ -30,9 +31,9 @@ impl PKey {
/// Create a new `PKey` containing a DSA key.
pub fn from_dsa(dsa: DSA) -> Result<PKey, ErrorStack> {
unsafe {
- let evp = try_ssl_null!(ffi::EVP_PKEY_new());
+ let evp = try!(cvt_p(ffi::EVP_PKEY_new()));
let pkey = PKey(evp);
- try_ssl!(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_DSA, dsa.as_ptr() as *mut _));
+ try!(cvt(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_DSA, dsa.as_ptr() as *mut _)));
mem::forget(dsa);
Ok(pkey)
}
@@ -42,10 +43,10 @@ impl PKey {
pub fn hmac(key: &[u8]) -> Result<PKey, ErrorStack> {
unsafe {
assert!(key.len() <= c_int::max_value() as usize);
- let key = try_ssl_null!(ffi::EVP_PKEY_new_mac_key(ffi::EVP_PKEY_HMAC,
- ptr::null_mut(),
- key.as_ptr() as *const _,
- key.len() as c_int));
+ let key = try!(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))
}
}
@@ -59,10 +60,10 @@ impl PKey {
ffi::init();
let mem_bio = try!(MemBioSlice::new(buf));
unsafe {
- let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.as_ptr(),
- ptr::null_mut(),
- None,
- ptr::null_mut()));
+ let evp = try!(cvt_p(ffi::PEM_read_bio_PrivateKey(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ None,
+ ptr::null_mut())));
Ok(PKey::from_ptr(evp))
}
}
@@ -79,10 +80,10 @@ impl PKey {
let mut cb = CallbackState::new(pass_cb);
let mem_bio = try!(MemBioSlice::new(buf));
unsafe {
- let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.as_ptr(),
- ptr::null_mut(),
- Some(invoke_passwd_cb::<F>),
- &mut cb as *mut _ as *mut c_void));
+ let evp = try!(cvt_p(ffi::PEM_read_bio_PrivateKey(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ Some(invoke_passwd_cb::<F>),
+ &mut cb as *mut _ as *mut c_void)));
Ok(PKey::from_ptr(evp))
}
}
@@ -92,10 +93,10 @@ impl PKey {
ffi::init();
let mem_bio = try!(MemBioSlice::new(buf));
unsafe {
- let evp = try_ssl_null!(ffi::PEM_read_bio_PUBKEY(mem_bio.as_ptr(),
- ptr::null_mut(),
- None,
- ptr::null_mut()));
+ let evp = try!(cvt_p(ffi::PEM_read_bio_PUBKEY(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ None,
+ ptr::null_mut())));
Ok(PKey::from_ptr(evp))
}
}
@@ -105,15 +106,15 @@ impl PKey {
unsafe {
// this needs to be a reference as the set1_RSA ups the reference count
let rsa_ptr = rsa.as_ptr();
- try_ssl!(ffi::EVP_PKEY_set1_RSA(self.0, rsa_ptr));
+ try!(cvt(ffi::EVP_PKEY_set1_RSA(self.0, rsa_ptr)));
Ok(())
}
}
/// Get a reference to the interal RSA key for direct access to the key components
- pub fn get_rsa(&self) -> Result<RSA, ErrorStack> {
+ pub fn rsa(&self) -> Result<RSA, ErrorStack> {
unsafe {
- let rsa = try_ssl_null!(ffi::EVP_PKEY_get1_RSA(self.0));
+ let rsa = try!(cvt_p(ffi::EVP_PKEY_get1_RSA(self.0)));
// this is safe as the ffi increments a reference counter to the internal key
Ok(RSA::from_ptr(rsa))
}
@@ -124,13 +125,13 @@ impl PKey {
pub fn private_key_to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
let mem_bio = try!(MemBio::new());
unsafe {
- try_ssl!(ffi::PEM_write_bio_PrivateKey(mem_bio.as_ptr(),
+ try!(cvt(ffi::PEM_write_bio_PrivateKey(mem_bio.as_ptr(),
self.0,
ptr::null(),
ptr::null_mut(),
-1,
None,
- ptr::null_mut()));
+ ptr::null_mut())));
}
Ok(mem_bio.get_buf().to_owned())
@@ -139,7 +140,9 @@ impl PKey {
/// Stores public key as a PEM
pub fn public_key_to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
let mem_bio = try!(MemBio::new());
- unsafe { try_ssl!(ffi::PEM_write_bio_PUBKEY(mem_bio.as_ptr(), self.0)) }
+ unsafe {
+ try!(cvt(ffi::PEM_write_bio_PUBKEY(mem_bio.as_ptr(), self.0)));
+ }
Ok(mem_bio.get_buf().to_owned())
}
diff --git a/openssl/src/crypto/rand.rs b/openssl/src/crypto/rand.rs
index 519449e9..c1c49e7b 100644
--- a/openssl/src/crypto/rand.rs
+++ b/openssl/src/crypto/rand.rs
@@ -1,13 +1,14 @@
use libc::c_int;
use ffi;
+
+use cvt;
use error::ErrorStack;
pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> {
unsafe {
ffi::init();
assert!(buf.len() <= c_int::max_value() as usize);
- try_ssl_if!(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int) != 1);
- Ok(())
+ cvt(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int)).map(|_| ())
}
}
diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs
index 1212ee3a..a6a4f2b7 100644
--- a/openssl/src/crypto/rsa.rs
+++ b/openssl/src/crypto/rsa.rs
@@ -4,6 +4,7 @@ use std::ptr;
use std::mem;
use libc::{c_int, c_void, c_char};
+use {cvt, cvt_p, cvt_n};
use bn::{BigNum, BigNumRef};
use bio::{MemBio, MemBioSlice};
use error::ErrorStack;
@@ -42,11 +43,11 @@ 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_ssl_null!(ffi::RSA_new()));
- try_ssl!(compat::set_key(rsa.0,
+ let rsa = RSA(try!(cvt_p(ffi::RSA_new())));
+ try!(cvt(compat::set_key(rsa.0,
n.as_ptr(),
e.as_ptr(),
- ptr::null_mut()));
+ ptr::null_mut())));
mem::forget((n, e));
Ok(rsa)
}
@@ -62,13 +63,13 @@ impl RSA {
qi: BigNum)
-> Result<RSA, ErrorStack> {
unsafe {
- let rsa = RSA(try_ssl_null!(ffi::RSA_new()));
- try_ssl!(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr()));
+ let rsa = RSA(try!(cvt_p(ffi::RSA_new())));
+ try!(cvt(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr())));
mem::forget((n, e, d));
- try_ssl!(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr()));
+ try!(cvt(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr())));
mem::forget((p, q));
- try_ssl!(compat::set_crt_params(rsa.0, dp.as_ptr(), dq.as_ptr(),
- qi.as_ptr()));
+ try!(cvt(compat::set_crt_params(rsa.0, dp.as_ptr(), dq.as_ptr(),
+ qi.as_ptr())));
mem::forget((dp, dq, qi));
Ok(rsa)
}
@@ -83,12 +84,9 @@ impl RSA {
/// The public exponent will be 65537.
pub fn generate(bits: u32) -> Result<RSA, ErrorStack> {
unsafe {
- let rsa = try_ssl_null!(ffi::RSA_new());
- let rsa = RSA(rsa);
- let e = try!(BigNum::new_from(ffi::RSA_F4 as u32));
-
- try_ssl!(ffi::RSA_generate_key_ex(rsa.0, bits as c_int, e.as_ptr(), ptr::null_mut()));
-
+ 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(rsa.0, bits as c_int, e.as_ptr(), ptr::null_mut())));
Ok(rsa)
}
}
@@ -97,10 +95,10 @@ impl RSA {
pub fn private_key_from_pem(buf: &[u8]) -> Result<RSA, ErrorStack> {
let mem_bio = try!(MemBioSlice::new(buf));
unsafe {
- let rsa = try_ssl_null!(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(),
- ptr::null_mut(),
- None,
- ptr::null_mut()));
+ let rsa = try!(cvt_p(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ None,
+ ptr::null_mut())));
Ok(RSA(rsa))
}
}
@@ -114,11 +112,10 @@ impl RSA {
unsafe {
let cb_ptr = &mut cb as *mut _ as *mut c_void;
- let rsa = try_ssl_null!(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(),
- ptr::null_mut(),
- Some(invoke_passwd_cb::<F>),
- cb_ptr));
-
+ let rsa = try!(cvt_p(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ Some(invoke_passwd_cb::<F>),
+ cb_ptr)));
Ok(RSA(rsa))
}
}
@@ -127,10 +124,10 @@ impl RSA {
pub fn public_key_from_pem(buf: &[u8]) -> Result<RSA, ErrorStack> {
let mem_bio = try!(MemBioSlice::new(buf));
unsafe {
- let rsa = try_ssl_null!(ffi::PEM_read_bio_RSA_PUBKEY(mem_bio.as_ptr(),
- ptr::null_mut(),
- None,
- ptr::null_mut()));
+ let rsa = try!(cvt_p(ffi::PEM_read_bio_RSA_PUBKEY(mem_bio.as_ptr(),
+ ptr::null_mut(),
+ None,
+ ptr::null_mut())));
Ok(RSA(rsa))
}
}
@@ -140,13 +137,13 @@ impl RSA {
let mem_bio = try!(MemBio::new());
unsafe {
- try_ssl!(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.as_ptr(),
- self.0,
- ptr::null(),
- ptr::null_mut(),
- 0,
- None,
- ptr::null_mut()));
+ try!(cvt(ffi::PEM_write_bio_RSAPrivateKey(mem_bio.as_ptr(),
+ self.0,
+ ptr::null(),
+ ptr::null_mut(),
+ 0,
+ None,
+ ptr::null_mut())));
}
Ok(mem_bio.get_buf().to_owned())
}
@@ -156,93 +153,113 @@ impl RSA {
let mem_bio = try!(MemBio::new());
unsafe {
- try_ssl!(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.as_ptr(), self.0))
- };
+ try!(cvt(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.as_ptr(), self.0)));
+ }
Ok(mem_bio.get_buf().to_owned())
}
- pub fn size(&self) -> Option<u32> {
- if self.n().is_some() {
- unsafe { Some(ffi::RSA_size(self.0) as u32) }
- } else {
- None
+ pub fn size(&self) -> usize {
+ unsafe {
+ assert!(self.n().is_some());
+
+ ffi::RSA_size(self.0) as usize
}
}
- /**
- * Decrypts data with the private key, using provided padding, returning the decrypted data.
- */
- pub fn private_decrypt(&self, from: &[u8], padding: Padding) -> Result<Vec<u8>, ErrorStack> {
+ /// Decrypts data using the private key, returning the number of decrypted bytes.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `self` has no private components, or if `to` is smaller
+ /// than `self.size()`.
+ pub fn private_decrypt(&self,
+ from: &[u8],
+ to: &mut [u8],
+ padding: Padding)
+ -> Result<usize, ErrorStack> {
assert!(self.d().is_some(), "private components missing");
- let k_len = self.size().expect("RSA missing an n");
- let mut to: Vec<u8> = vec![0; k_len as usize];
+ assert!(from.len() <= i32::max_value() as usize);
+ assert!(to.len() >= self.size());
unsafe {
- let enc_len = try_ssl_returns_size!(ffi::RSA_private_decrypt(from.len() as i32,
- from.as_ptr(),
- to.as_mut_ptr(),
- self.0,
- padding.0));
- to.truncate(enc_len as usize);
- Ok(to)
+ let len = try!(cvt_n(ffi::RSA_private_decrypt(from.len() as c_int,
+ from.as_ptr(),
+ to.as_mut_ptr(),
+ self.0,
+ padding.0)));
+ Ok(len as usize)
}
}
- /**
- * Encrypts data with the private key, using provided padding, returning the encrypted data.
- */
- pub fn private_encrypt(&self, from: &[u8], padding: Padding) -> Result<Vec<u8>, ErrorStack> {
+ /// Encrypts data using the private key, returning the number of encrypted bytes.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `self` has no private components, or if `to` is smaller
+ /// than `self.size()`.
+ pub fn private_encrypt(&self,
+ from: &[u8],
+ to: &mut [u8],
+ padding: Padding)
+ -> Result<usize, ErrorStack> {
assert!(self.d().is_some(), "private components missing");
- let k_len = self.size().expect("RSA missing an n");
- let mut to:Vec<u8> = vec![0; k_len as usize];
+ assert!(from.len() <= i32::max_value() as usize);
+ assert!(to.len() >= self.size());
unsafe {
- let enc_len = try_ssl_returns_size!(ffi::RSA_private_encrypt(from.len() as c_int,
- from.as_ptr(),
- to.as_mut_ptr(),
- self.0,
- padding.0));
- assert!(enc_len as u32 == k_len);
-
- Ok(to)
+ let len = try!(cvt_n(ffi::RSA_private_encrypt(from.len() as c_int,
+ from.as_ptr(),
+ to.as_mut_ptr(),
+ self.0,
+ padding.0)));
+ Ok(len as usize)
}
}
- /**
- * Decrypts data with the public key, using provided padding, returning the decrypted data.
- */
- pub fn public_decrypt(&self, from: &[u8], padding: Padding) -> Result<Vec<u8>, ErrorStack> {
- let k_len = self.size().expect("RSA missing an n");
- let mut to: Vec<u8> = vec![0; k_len as usize];
+ /// Decrypts data using the public key, returning the number of decrypted bytes.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `to` is smaller than `self.size()`.
+ pub fn public_decrypt(&self,
+ from: &[u8],
+ to: &mut [u8],
+ padding: Padding)
+ -> Result<usize, ErrorStack> {
+ assert!(from.len() <= i32::max_value() as usize);
+ assert!(to.len() >= self.size());
unsafe {
- let enc_len = try_ssl_returns_size!(ffi::RSA_public_decrypt(from.len() as i32,
- from.as_ptr(),
- to.as_mut_ptr(),
- self.0,
- padding.0));
- to.truncate(enc_len as usize);
- Ok(to)
+ let len = try!(cvt_n(ffi::RSA_public_decrypt(from.len() as c_int,
+ from.as_ptr(),
+ to.as_mut_ptr(),
+ self.0,
+ padding.0)));
+ Ok(len as usize)
}
}
- /**
- * Encrypts data with the public key, using provided padding, returning the encrypted data.
- */
- pub fn public_encrypt(&self, from: &[u8], padding: Padding) -> Result<Vec<u8>, ErrorStack> {
- let k_len = self.size().expect("RSA missing an n");
- let mut to:Vec<u8> = vec![0; k_len as usize];
+ /// Encrypts data using the private key, returning the number of encrypted bytes.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `to` is smaller than `self.size()`.
+ pub fn public_encrypt(&self,
+ from: &[u8],
+ to: &mut [u8],
+ padding: Padding)
+ -> Result<usize, ErrorStack> {
+ assert!(from.len() <= i32::max_value() as usize);
+ assert!(to.len() >= self.size());
unsafe {
- let enc_len = try_ssl_returns_size!(ffi::RSA_public_encrypt(from.len() as c_int,
- from.as_ptr(),
- to.as_mut_ptr(),
- self.0,
- padding.0));
- assert!(enc_len as u32 == k_len);
-
- Ok(to)
+ let len = try!(cvt_n(ffi::RSA_public_encrypt(from.len() as c_int,
+ from.as_ptr(),
+ to.as_mut_ptr(),
+ self.0,
+ padding.0)));
+ Ok(len as usize)
}
}
@@ -424,55 +441,47 @@ mod test {
let key = include_bytes!("../../test/rsa.pem.pub");
let public_key = RSA::public_key_from_pem(key).unwrap();
- let original_data: Vec<u8> = "This is test".to_string().into_bytes();
- let result = public_key.public_encrypt(&original_data, Padding::pkcs1()).unwrap();
-
- assert_eq!(result.len(), 256);
+ let mut result = vec![0; public_key.size()];
+ let original_data = b"This is test";
+ let len = public_key.public_encrypt(original_data, &mut result, Padding::pkcs1()).unwrap();
+ assert_eq!(len, 256);
let pkey = include_bytes!("../../test/rsa.pem");
let private_key = RSA::private_key_from_pem(pkey).unwrap();
- let dec_result = private_key.private_decrypt(&result, Padding::pkcs1()).unwrap();
+ let mut dec_result = vec![0; private_key.size()];
+ let len = private_key.private_decrypt(&result, &mut dec_result, Padding::pkcs1()).unwrap();
- assert_eq!(dec_result, original_data);
+ assert_eq!(&dec_result[..len], original_data);
}
#[test]
fn test_private_encrypt() {
- let k0 = super::RSA::generate(512).unwrap();
- let k0pkey = k0.public_key_to_pem().unwrap();
- let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap();
+ let k0 = super::RSA::generate(512).unwrap();
+ let k0pkey = k0.public_key_to_pem().unwrap();
+ let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap();
- let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8);
+ let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
- let emsg = k0.private_encrypt(&msg, Padding::pkcs1()).unwrap();
- let dmsg = k1.public_decrypt(&emsg, Padding::pkcs1()).unwrap();
- assert!(msg == dmsg);
+ let mut emesg = vec![0; k0.size()];
+ k0.private_encrypt(&msg, &mut emesg, Padding::pkcs1()).unwrap();
+ let mut dmesg = vec![0; k1.size()];
+ let len = k1.public_decrypt(&emesg, &mut dmesg, Padding::pkcs1()).unwrap();
+ assert_eq!(msg, &dmesg[..len]);
}
#[test]
fn test_public_encrypt() {
let k0 = super::RSA::generate(512).unwrap();
- let k0pkey = k0.public_key_to_pem().unwrap();
- let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap();
-
- let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8);
-
- let emsg = k1.public_encrypt(&msg, Padding::pkcs1_oaep()).unwrap();
- let dmsg = k0.private_decrypt(&emsg, Padding::pkcs1_oaep()).unwrap();
- assert!(msg == dmsg);
- }
-
- #[test]
- fn test_public_encrypt_pkcs() {
- let k0 = super::RSA::generate(512).unwrap();
- let k0pkey = k0.public_key_to_pem().unwrap();
- let k1 = super::RSA::public_key_from_pem(&k0pkey).unwrap();
+ let k0pkey = k0.private_key_to_pem().unwrap();
+ let k1 = super::RSA::private_key_from_pem(&k0pkey).unwrap();
- let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8);
+ let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
- let emsg = k1.public_encrypt(&msg, super::Padding::pkcs1()).unwrap();
- let dmsg = k0.private_decrypt(&emsg, super::Padding::pkcs1()).unwrap();
- assert!(msg == dmsg);
+ let mut emesg = vec![0; k0.size()];
+ k0.public_encrypt(&msg, &mut emesg, Padding::pkcs1()).unwrap();
+ let mut dmesg = vec![0; k1.size()];
+ let len = k1.private_decrypt(&emesg, &mut dmesg, Padding::pkcs1()).unwrap();
+ assert_eq!(msg, &dmesg[..len]);
}
}
diff --git a/openssl/src/crypto/sign.rs b/openssl/src/crypto/sign.rs
index fdedd4d5..41009149 100644
--- a/openssl/src/crypto/sign.rs
+++ b/openssl/src/crypto/sign.rs
@@ -59,6 +59,7 @@ use std::io::{self, Write};
use std::marker::PhantomData;
use std::ptr;
+use {cvt, cvt_p};
use crypto::hash::MessageDigest;
use crypto::pkey::PKey;
use error::ErrorStack;
@@ -83,7 +84,7 @@ impl<'a> Signer<'a> {
unsafe {
ffi::init();
- let ctx = try_ssl_null!(EVP_MD_CTX_new());
+ let ctx = try!(cvt_p(EVP_MD_CTX_new()));
let r = ffi::EVP_DigestSignInit(ctx,
ptr::null_mut(),
type_.as_ptr(),
@@ -93,25 +94,22 @@ impl<'a> Signer<'a> {
EVP_MD_CTX_free(ctx);
return Err(ErrorStack::get());
}
-
Ok(Signer(ctx, PhantomData))
}
}
pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> {
unsafe {
- try_ssl_if!(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len()) != 1);
- Ok(())
+ cvt(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len())).map(|_| ())
}
}
pub fn finish(&self) -> Result<Vec<u8>, ErrorStack> {
unsafe {
let mut len = 0;
- try_ssl_if!(ffi::EVP_DigestSignFinal(self.0, ptr::null_mut(), &mut len) != 1);
+ try!(cvt(ffi::EVP_DigestSignFinal(self.0, ptr::null_mut(), &mut len)));
let mut buf = vec![0; len];
- try_ssl_if!(ffi::EVP_DigestSignFinal(self.0, buf.as_mut_ptr() as *mut _, &mut len)
- != 1);
+ try!(cvt(ffi::EVP_DigestSignFinal(self.0, 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)
@@ -145,7 +143,7 @@ impl<'a> Verifier<'a> {
unsafe {
ffi::init();
- let ctx = try_ssl_null!(EVP_MD_CTX_new());
+ let ctx = try!(cvt_p(EVP_MD_CTX_new()));
let r = ffi::EVP_DigestVerifyInit(ctx,
ptr::null_mut(),
type_.as_ptr(),
@@ -162,8 +160,7 @@ impl<'a> Verifier<'a> {
pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> {
unsafe {
- try_ssl_if!(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len()) != 1);
- Ok(())
+ cvt(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len())).map(|_| ())
}
}
diff --git a/openssl/src/crypto/symm.rs b/openssl/src/crypto/symm.rs
index 8ac6b7cf..65f0addb 100644
--- a/openssl/src/crypto/symm.rs
+++ b/openssl/src/crypto/symm.rs
@@ -3,6 +3,7 @@ use std::ptr;
use libc::c_int;
use ffi;
+use {cvt, cvt_p};
use error::ErrorStack;
#[derive(Copy, Clone)]
@@ -170,7 +171,7 @@ impl Crypter {
ffi::init();
unsafe {
- let ctx = try_ssl_null!(ffi::EVP_CIPHER_CTX_new());
+ let ctx = try!(cvt_p(ffi::EVP_CIPHER_CTX_new()));
let crypter = Crypter {
ctx: ctx,
block_size: t.block_size(),
@@ -181,15 +182,15 @@ impl Crypter {
Mode::Decrypt => 0,
};
- try_ssl!(ffi::EVP_CipherInit_ex(crypter.ctx,
- t.as_ptr(),
- ptr::null_mut(),
- ptr::null_mut(),
- ptr::null_mut(),
- mode));
+ try!(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_ssl!(ffi::EVP_CIPHER_CTX_set_key_length(crypter.ctx, key.len() as c_int));
+ try!(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()) {
@@ -200,12 +201,12 @@ impl Crypter {
(Some(_), None) | (None, None) => ptr::null_mut(),
(None, Some(_)) => panic!("an IV is required for this cipher"),
};
- try_ssl!(ffi::EVP_CipherInit_ex(crypter.ctx,
+ try!(cvt(ffi::EVP_CipherInit_ex(crypter.ctx,
ptr::null(),
ptr::null_mut(),
key,
iv,
- mode));
+ mode)));
Ok(crypter)
}
@@ -237,11 +238,11 @@ impl Crypter {
let mut outl = output.len() as c_int;
let inl = input.len() as c_int;
- try_ssl!(ffi::EVP_CipherUpdate(self.ctx,
+ try!(cvt(ffi::EVP_CipherUpdate(self.ctx,
output.as_mut_ptr(),
&mut outl,
input.as_ptr(),
- inl));
+ inl)));
Ok(outl as usize)
}
@@ -262,7 +263,7 @@ 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_ssl!(ffi::EVP_CipherFinal(self.ctx, output.as_mut_ptr(), &mut outl));
+ try!(cvt(ffi::EVP_CipherFinal(self.ctx, output.as_mut_ptr(), &mut outl)));
Ok(outl as usize)
}