aboutsummaryrefslogtreecommitdiff
path: root/openssl/src/crypto
diff options
context:
space:
mode:
authorSteven Fackler <[email protected]>2016-10-22 09:16:38 -0700
committerSteven Fackler <[email protected]>2016-10-22 09:16:38 -0700
commit98b7f2f9352e4d92b44245d0737f9a45adb4ae2b (patch)
tree983929f8b6cd8be9e42e226ac74a5ddc5f29ccd5 /openssl/src/crypto
parentProperly propagate panics (diff)
downloadrust-openssl-98b7f2f9352e4d92b44245d0737f9a45adb4ae2b.tar.xz
rust-openssl-98b7f2f9352e4d92b44245d0737f9a45adb4ae2b.zip
Flatten crypto module
Diffstat (limited to 'openssl/src/crypto')
-rw-r--r--openssl/src/crypto/dsa.rs265
-rw-r--r--openssl/src/crypto/hash.rs350
-rw-r--r--openssl/src/crypto/memcmp.rs39
-rw-r--r--openssl/src/crypto/mod.rs28
-rw-r--r--openssl/src/crypto/pkcs12.rs119
-rw-r--r--openssl/src/crypto/pkcs5.rs192
-rw-r--r--openssl/src/crypto/pkey.rs193
-rw-r--r--openssl/src/crypto/rand.rs24
-rw-r--r--openssl/src/crypto/rsa.rs487
-rw-r--r--openssl/src/crypto/sign.rs397
-rw-r--r--openssl/src/crypto/symm.rs558
-rw-r--r--openssl/src/crypto/util.rs61
12 files changed, 0 insertions, 2713 deletions
diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs
deleted file mode 100644
index f5b0f4e4..00000000
--- a/openssl/src/crypto/dsa.rs
+++ /dev/null
@@ -1,265 +0,0 @@
-use ffi;
-use std::fmt;
-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 {
- 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())));
- Ok(dsa)
- }
- }
-
- /// Generate a key pair from the initialized parameters
- pub fn generate(self) -> Result<DSA, ErrorStack> {
- unsafe {
- try!(cvt(ffi::DSA_generate_key(self.0)));
- let dsa = DSA(self.0);
- ::std::mem::forget(self);
- Ok(dsa)
- }
- }
-}
-
-impl Drop for DSAParams {
- fn drop(&mut self) {
- unsafe {
- ffi::DSA_free(self.0);
- }
- }
-}
-
-pub struct DSA(*mut ffi::DSA);
-
-impl Drop for DSA {
- fn drop(&mut self) {
- unsafe {
- ffi::DSA_free(self.0);
- }
- }
-}
-
-impl DSA {
- pub unsafe fn from_ptr(dsa: *mut ffi::DSA) -> DSA {
- DSA(dsa)
- }
-
- /// Generate a DSA key pair
- /// For more complicated key generation scenarios see the `DSAParams` type
- pub fn generate(size: u32) -> Result<DSA, ErrorStack> {
- let params = try!(DSAParams::with_size(size));
- params.generate()
- }
-
- /// Reads a DSA private key from PEM formatted data.
- pub fn private_key_from_pem(buf: &[u8]) -> Result<DSA, ErrorStack> {
- ffi::init();
- let mem_bio = try!(MemBioSlice::new(buf));
-
- unsafe {
- let dsa = try!(cvt_p(ffi::PEM_read_bio_DSAPrivateKey(mem_bio.as_ptr(),
- ptr::null_mut(),
- None,
- ptr::null_mut())));
- Ok(DSA(dsa))
- }
- }
-
- /// Read a private key from PEM supplying a password callback to be invoked if the private key
- /// is encrypted.
- ///
- /// The callback will be passed the password buffer and should return the number of characters
- /// placed into the buffer.
- pub fn private_key_from_pem_cb<F>(buf: &[u8], pass_cb: F) -> Result<DSA, ErrorStack>
- where F: FnOnce(&mut [c_char]) -> usize
- {
- ffi::init();
- let mut cb = CallbackState::new(pass_cb);
- let mem_bio = try!(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(mem_bio.as_ptr(),
- ptr::null_mut(),
- Some(invoke_passwd_cb::<F>),
- cb_ptr)));
- Ok(DSA(dsa))
- }
- }
-
- /// Writes an DSA private key as unencrypted PEM formatted data
- pub fn private_key_to_pem(&self) -> Result<Vec<u8>, ErrorStack>
- {
- assert!(self.has_private_key());
- let mem_bio = try!(MemBio::new());
-
- unsafe {
- 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())
- }
-
- /// Reads an DSA public key from PEM formatted data.
- pub fn public_key_from_pem(buf: &[u8]) -> Result<DSA, ErrorStack>
- {
- ffi::init();
-
- let mem_bio = try!(MemBioSlice::new(buf));
- unsafe {
- 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))
- }
- }
-
- /// 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!(cvt(ffi::PEM_write_bio_DSA_PUBKEY(mem_bio.as_ptr(), self.0)));
- }
- Ok(mem_bio.get_buf().to_owned())
- }
-
- pub fn size(&self) -> Option<u32> {
- if self.q().is_some() {
- unsafe { Some(ffi::DSA_size(self.0) as u32) }
- } else {
- None
- }
- }
-
- pub fn as_ptr(&self) -> *mut ffi::DSA {
- self.0
- }
-
- pub fn p(&self) -> Option<&BigNumRef> {
- unsafe {
- let p = compat::pqg(self.0)[0];
- if p.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(p as *mut _))
- }
- }
- }
-
- pub fn q(&self) -> Option<&BigNumRef> {
- unsafe {
- let q = compat::pqg(self.0)[1];
- if q.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(q as *mut _))
- }
- }
- }
-
- pub fn g(&self) -> Option<&BigNumRef> {
- unsafe {
- let g = compat::pqg(self.0)[2];
- if g.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(g as *mut _))
- }
- }
- }
-
- pub fn has_public_key(&self) -> bool {
- unsafe { !compat::keys(self.0)[0].is_null() }
- }
-
- pub fn has_private_key(&self) -> bool {
- unsafe { !compat::keys(self.0)[1].is_null() }
- }
-}
-
-#[cfg(ossl110)]
-mod compat {
- use std::ptr;
- use ffi::{self, BIGNUM, DSA};
-
- pub unsafe fn pqg(d: *const DSA) -> [*const BIGNUM; 3] {
- let (mut p, mut q, mut g) = (ptr::null(), ptr::null(), ptr::null());
- ffi::DSA_get0_pqg(d, &mut p, &mut q, &mut g);
- [p, q, g]
- }
-
- pub unsafe fn keys(d: *const DSA) -> [*const BIGNUM; 2] {
- let (mut pub_key, mut priv_key) = (ptr::null(), ptr::null());
- ffi::DSA_get0_key(d, &mut pub_key, &mut priv_key);
- [pub_key, priv_key]
- }
-}
-
-#[cfg(ossl10x)]
-mod compat {
- use ffi::{BIGNUM, DSA};
-
- pub unsafe fn pqg(d: *const DSA) -> [*const BIGNUM; 3] {
- [(*d).p, (*d).q, (*d).g]
- }
-
- pub unsafe fn keys(d: *const DSA) -> [*const BIGNUM; 2] {
- [(*d).pub_key, (*d).priv_key]
- }
-}
-
-impl fmt::Debug for DSA {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "DSA")
- }
-}
-
-#[cfg(test)]
-mod test {
- use libc::c_char;
-
- use super::*;
-
- #[test]
- pub fn test_generate() {
- DSA::generate(1024).unwrap();
- }
-
- #[test]
- pub fn test_password() {
- let mut password_queried = false;
- let key = include_bytes!("../../test/dsa-encrypted.pem");
- DSA::private_key_from_pem_cb(key, |password| {
- password_queried = true;
- password[0] = b'm' as c_char;
- password[1] = b'y' as c_char;
- password[2] = b'p' as c_char;
- password[3] = b'a' as c_char;
- password[4] = b's' as c_char;
- password[5] = b's' as c_char;
- 6
- }).unwrap();
-
- assert!(password_queried);
- }
-}
diff --git a/openssl/src/crypto/hash.rs b/openssl/src/crypto/hash.rs
deleted file mode 100644
index ec265631..00000000
--- a/openssl/src/crypto/hash.rs
+++ /dev/null
@@ -1,350 +0,0 @@
-use std::io::prelude::*;
-use std::io;
-use ffi;
-
-#[cfg(ossl110)]
-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)]
-pub struct MessageDigest(*const ffi::EVP_MD);
-
-impl MessageDigest {
- pub fn md5() -> MessageDigest {
- unsafe {
- MessageDigest(ffi::EVP_md5())
- }
- }
-
- pub fn sha1() -> MessageDigest {
- unsafe {
- MessageDigest(ffi::EVP_sha1())
- }
- }
-
- pub fn sha224() -> MessageDigest {
- unsafe {
- MessageDigest(ffi::EVP_sha224())
- }
- }
-
- pub fn sha256() -> MessageDigest {
- unsafe {
- MessageDigest(ffi::EVP_sha256())
- }
- }
-
- pub fn sha384() -> MessageDigest {
- unsafe {
- MessageDigest(ffi::EVP_sha384())
- }
- }
-
- pub fn sha512() -> MessageDigest {
- unsafe {
- MessageDigest(ffi::EVP_sha512())
- }
- }
-
- pub fn ripemd160() -> MessageDigest {
- unsafe {
- MessageDigest(ffi::EVP_ripemd160())
- }
- }
-
- pub fn as_ptr(&self) -> *const ffi::EVP_MD {
- self.0
- }
-}
-
-#[derive(PartialEq, Copy, Clone)]
-enum State {
- Reset,
- Updated,
- Finalized,
-}
-
-use self::State::*;
-
-/// Provides message digest (hash) computation.
-///
-/// # Examples
-///
-/// Calculate a hash in one go.
-///
-/// ```
-/// use openssl::crypto::hash::{hash, MessageDigest};
-///
-/// let data = b"\x42\xF4\x97\xE0";
-/// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2";
-/// let res = hash(MessageDigest::md5(), data).unwrap();
-/// assert_eq!(res, spec);
-/// ```
-///
-/// Use the `Write` trait to supply the input in chunks.
-///
-/// ```
-/// use openssl::crypto::hash::{Hasher, MessageDigest};
-///
-/// let data = [b"\x42\xF4", b"\x97\xE0"];
-/// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2";
-/// let mut h = Hasher::new(MessageDigest::md5()).unwrap();
-/// h.update(data[0]).unwrap();
-/// h.update(data[1]).unwrap();
-/// let res = h.finish().unwrap();
-/// assert_eq!(res, spec);
-/// ```
-///
-/// # Warning
-///
-/// Don't actually use MD5 and SHA-1 hashes, they're not secure anymore.
-///
-/// Don't ever hash passwords, use `crypto::pkcs5` or bcrypt/scrypt instead.
-pub struct Hasher {
- ctx: *mut ffi::EVP_MD_CTX,
- md: *const ffi::EVP_MD,
- type_: MessageDigest,
- state: State,
-}
-
-impl Hasher {
- /// Creates a new `Hasher` with the specified hash type.
- pub fn new(ty: MessageDigest) -> Result<Hasher, ErrorStack> {
- ffi::init();
-
- let ctx = unsafe { try!(cvt_p(EVP_MD_CTX_new())) };
-
- let mut h = Hasher {
- ctx: ctx,
- md: ty.as_ptr(),
- type_: ty,
- state: Finalized,
- };
- try!(h.init());
- Ok(h)
- }
-
- fn init(&mut self) -> Result<(), ErrorStack> {
- match self.state {
- Reset => return Ok(()),
- Updated => {
- try!(self.finish());
- }
- Finalized => (),
- }
- unsafe { try!(cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))); }
- self.state = Reset;
- Ok(())
- }
-
- /// Feeds data into the hasher.
- pub fn update(&mut self, data: &[u8]) -> Result<(), ErrorStack> {
- if self.state == Finalized {
- try!(self.init());
- }
- unsafe {
- try!(cvt(ffi::EVP_DigestUpdate(self.ctx,
- data.as_ptr() as *mut _,
- data.len())));
- }
- self.state = Updated;
- Ok(())
- }
-
- /// Returns the hash of the data written since creation or
- /// the last `finish` and resets the hasher.
- pub fn finish(&mut self) -> Result<Vec<u8>, ErrorStack> {
- if self.state == Finalized {
- try!(self.init());
- }
- unsafe {
- let mut len = ffi::EVP_MAX_MD_SIZE;
- let mut res = vec![0; len as usize];
- try!(cvt(ffi::EVP_DigestFinal_ex(self.ctx, res.as_mut_ptr(), &mut len)));
- res.truncate(len as usize);
- self.state = Finalized;
- Ok(res)
- }
- }
-}
-
-impl Write for Hasher {
- #[inline]
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- try!(self.update(buf));
- Ok(buf.len())
- }
-
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
-}
-
-impl Clone for Hasher {
- fn clone(&self) -> Hasher {
- let ctx = unsafe {
- let ctx = EVP_MD_CTX_new();
- assert!(!ctx.is_null());
- let r = ffi::EVP_MD_CTX_copy_ex(ctx, self.ctx);
- assert_eq!(r, 1);
- ctx
- };
- Hasher {
- ctx: ctx,
- md: self.md,
- type_: self.type_,
- state: self.state,
- }
- }
-}
-
-impl Drop for Hasher {
- fn drop(&mut self) {
- unsafe {
- if self.state != Finalized {
- drop(self.finish());
- }
- EVP_MD_CTX_free(self.ctx);
- }
- }
-}
-
-/// Computes the hash of the `data` with the hash `t`.
-pub fn hash(t: MessageDigest, data: &[u8]) -> Result<Vec<u8>, ErrorStack> {
- let mut h = try!(Hasher::new(t));
- try!(h.update(data));
- h.finish()
-}
-
-#[cfg(test)]
-mod tests {
- use serialize::hex::{FromHex, ToHex};
- use super::{hash, Hasher, MessageDigest};
- use std::io::prelude::*;
-
- fn hash_test(hashtype: MessageDigest, hashtest: &(&str, &str)) {
- let res = hash(hashtype, &*hashtest.0.from_hex().unwrap()).unwrap();
- assert_eq!(res.to_hex(), hashtest.1);
- }
-
- fn hash_recycle_test(h: &mut Hasher, hashtest: &(&str, &str)) {
- let _ = h.write_all(&*hashtest.0.from_hex().unwrap()).unwrap();
- let res = h.finish().unwrap();
- assert_eq!(res.to_hex(), hashtest.1);
- }
-
- // Test vectors from http://www.nsrl.nist.gov/testdata/
- #[allow(non_upper_case_globals)]
- const md5_tests: [(&'static str, &'static str); 13] = [("",
- "d41d8cd98f00b204e9800998ecf8427e"),
- ("7F",
- "83acb6e67e50e31db6ed341dd2de1595"),
- ("EC9C",
- "0b07f0d4ca797d8ac58874f887cb0b68"),
- ("FEE57A",
- "e0d583171eb06d56198fc0ef22173907"),
- ("42F497E0",
- "7c430f178aefdf1487fee7144e9641e2"),
- ("C53B777F1C",
- "75ef141d64cb37ec423da2d9d440c925"),
- ("89D5B576327B",
- "ebbaf15eb0ed784c6faa9dc32831bf33"),
- ("5D4CCE781EB190",
- "ce175c4b08172019f05e6b5279889f2c"),
- ("81901FE94932D7B9",
- "cd4d2f62b8cdb3a0cf968a735a239281"),
- ("C9FFDEE7788EFB4EC9",
- "e0841a231ab698db30c6c0f3f246c014"),
- ("66AC4B7EBA95E53DC10B",
- "a3b3cea71910d9af56742aa0bb2fe329"),
- ("A510CD18F7A56852EB0319",
- "577e216843dd11573574d3fb209b97d8"),
- ("AAED18DBE8938C19ED734A8D",
- "6f80fb775f27e0a4ce5c2f42fc72c5f1")];
-
- #[test]
- fn test_md5() {
- for test in md5_tests.iter() {
- hash_test(MessageDigest::md5(), test);
- }
- }
-
- #[test]
- fn test_md5_recycle() {
- let mut h = Hasher::new(MessageDigest::md5()).unwrap();
- for test in md5_tests.iter() {
- hash_recycle_test(&mut h, test);
- }
- }
-
- #[test]
- fn test_finish_twice() {
- let mut h = Hasher::new(MessageDigest::md5()).unwrap();
- h.write_all(&*md5_tests[6].0.from_hex().unwrap()).unwrap();
- h.finish().unwrap();
- let res = h.finish().unwrap();
- let null = hash(MessageDigest::md5(), &[]).unwrap();
- assert_eq!(res, null);
- }
-
- #[test]
- fn test_clone() {
- let i = 7;
- let inp = md5_tests[i].0.from_hex().unwrap();
- assert!(inp.len() > 2);
- let p = inp.len() / 2;
- let h0 = Hasher::new(MessageDigest::md5()).unwrap();
-
- println!("Clone a new hasher");
- let mut h1 = h0.clone();
- h1.write_all(&inp[..p]).unwrap();
- {
- println!("Clone an updated hasher");
- let mut h2 = h1.clone();
- h2.write_all(&inp[p..]).unwrap();
- let res = h2.finish().unwrap();
- assert_eq!(res.to_hex(), md5_tests[i].1);
- }
- h1.write_all(&inp[p..]).unwrap();
- let res = h1.finish().unwrap();
- assert_eq!(res.to_hex(), md5_tests[i].1);
-
- println!("Clone a finished hasher");
- let mut h3 = h1.clone();
- h3.write_all(&*md5_tests[i + 1].0.from_hex().unwrap()).unwrap();
- let res = h3.finish().unwrap();
- assert_eq!(res.to_hex(), md5_tests[i + 1].1);
- }
-
- #[test]
- fn test_sha1() {
- let tests = [("616263", "a9993e364706816aba3e25717850c26c9cd0d89d")];
-
- for test in tests.iter() {
- hash_test(MessageDigest::sha1(), test);
- }
- }
-
- #[test]
- fn test_sha256() {
- let tests = [("616263",
- "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")];
-
- for test in tests.iter() {
- hash_test(MessageDigest::sha256(), test);
- }
- }
-
- #[test]
- fn test_ripemd160() {
- let tests = [("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")];
-
- for test in tests.iter() {
- hash_test(MessageDigest::ripemd160(), test);
- }
- }
-}
diff --git a/openssl/src/crypto/memcmp.rs b/openssl/src/crypto/memcmp.rs
deleted file mode 100644
index cf08bdb5..00000000
--- a/openssl/src/crypto/memcmp.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-use libc::size_t;
-use ffi;
-
-/// Returns `true` iff `a` and `b` contain the same bytes.
-///
-/// This operation takes an amount of time dependent on the length of the two
-/// arrays given, but is independent of the contents of a and b.
-///
-/// # Failure
-///
-/// This function will panic the current task if `a` and `b` do not have the same
-/// length.
-pub fn eq(a: &[u8], b: &[u8]) -> bool {
- assert!(a.len() == b.len());
- let ret = unsafe {
- ffi::CRYPTO_memcmp(a.as_ptr() as *const _,
- b.as_ptr() as *const _,
- a.len() as size_t)
- };
- ret == 0
-}
-
-#[cfg(test)]
-mod tests {
- use super::eq;
-
- #[test]
- fn test_eq() {
- assert!(eq(&[], &[]));
- assert!(eq(&[1], &[1]));
- assert!(!eq(&[1, 2, 3], &[1, 2, 4]));
- }
-
- #[test]
- #[should_panic]
- fn test_diff_lens() {
- eq(&[], &[1]);
- }
-}
diff --git a/openssl/src/crypto/mod.rs b/openssl/src/crypto/mod.rs
deleted file mode 100644
index 0db23bcc..00000000
--- a/openssl/src/crypto/mod.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright 2011 Google Inc.
-// 2013 Jack Lloyd
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-mod util;
-pub mod dsa;
-pub mod hash;
-pub mod memcmp;
-pub mod pkcs12;
-pub mod pkcs5;
-pub mod pkey;
-pub mod rand;
-pub mod rsa;
-pub mod sign;
-pub mod symm;
-
diff --git a/openssl/src/crypto/pkcs12.rs b/openssl/src/crypto/pkcs12.rs
deleted file mode 100644
index 846b7baf..00000000
--- a/openssl/src/crypto/pkcs12.rs
+++ /dev/null
@@ -1,119 +0,0 @@
-//! PKCS #12 archives.
-
-use ffi;
-use libc::{c_long, c_uchar};
-use std::cmp;
-use std::ptr;
-use std::ffi::CString;
-
-use {cvt, cvt_p};
-use crypto::pkey::PKey;
-use error::ErrorStack;
-use x509::X509;
-
-/// A PKCS #12 archive.
-pub struct Pkcs12(*mut ffi::PKCS12);
-
-impl Drop for Pkcs12 {
- fn drop(&mut self) {
- unsafe { ffi::PKCS12_free(self.0); }
- }
-}
-
-impl Pkcs12 {
- /// Deserializes a `Pkcs12` structure from DER-encoded data.
- pub fn from_der(der: &[u8]) -> Result<Pkcs12, ErrorStack> {
- unsafe {
- 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!(cvt_p(ffi::d2i_PKCS12(ptr::null_mut(), &mut ptr, length)));
- Ok(Pkcs12(p12))
- }
- }
-
- /// Extracts the contents of the `Pkcs12`.
- pub fn parse(&self, pass: &str) -> Result<ParsedPkcs12, ErrorStack> {
- unsafe {
- let pass = CString::new(pass).unwrap();
-
- let mut pkey = ptr::null_mut();
- let mut cert = ptr::null_mut();
- let mut chain = ptr::null_mut();
-
- 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);
- let chain = chain as *mut _;
-
- let mut chain_out = vec![];
- for i in 0..compat::OPENSSL_sk_num(chain) {
- let x509 = compat::OPENSSL_sk_value(chain, i);
- chain_out.push(X509::from_ptr(x509 as *mut _));
- }
- compat::OPENSSL_sk_free(chain as *mut _);
-
- Ok(ParsedPkcs12 {
- pkey: pkey,
- cert: cert,
- chain: chain_out,
- _p: (),
- })
- }
- }
-}
-
-pub struct ParsedPkcs12 {
- pub pkey: PKey,
- pub cert: X509,
- pub chain: Vec<X509>,
- _p: (),
-}
-
-#[cfg(ossl110)]
-mod compat {
- pub use ffi::OPENSSL_sk_free;
- pub use ffi::OPENSSL_sk_num;
- pub use ffi::OPENSSL_sk_value;
-}
-
-#[cfg(ossl10x)]
-#[allow(bad_style)]
-mod compat {
- use libc::{c_int, c_void};
- use ffi;
-
- pub use ffi::sk_free as OPENSSL_sk_free;
-
- pub unsafe fn OPENSSL_sk_num(stack: *mut ffi::_STACK) -> c_int {
- (*stack).num
- }
-
- pub unsafe fn OPENSSL_sk_value(stack: *const ffi::_STACK, idx: c_int)
- -> *mut c_void {
- *(*stack).data.offset(idx as isize) as *mut c_void
- }
-}
-
-#[cfg(test)]
-mod test {
- use crypto::hash::MessageDigest;
- use serialize::hex::ToHex;
-
- use super::*;
-
- #[test]
- fn parse() {
- let der = include_bytes!("../../test/identity.p12");
- let pkcs12 = Pkcs12::from_der(der).unwrap();
- let parsed = pkcs12.parse("mypass").unwrap();
-
- assert_eq!(parsed.cert.fingerprint(MessageDigest::sha1()).unwrap().to_hex(),
- "59172d9313e84459bcff27f967e79e6e9217e584");
-
- assert_eq!(parsed.chain.len(), 1);
- assert_eq!(parsed.chain[0].fingerprint(MessageDigest::sha1()).unwrap().to_hex(),
- "c0cbdf7cdd03c9773e5468e1f6d2da7d5cbb1875");
- }
-}
diff --git a/openssl/src/crypto/pkcs5.rs b/openssl/src/crypto/pkcs5.rs
deleted file mode 100644
index 8bcb9b31..00000000
--- a/openssl/src/crypto/pkcs5.rs
+++ /dev/null
@@ -1,192 +0,0 @@
-use libc::c_int;
-use std::ptr;
-use ffi;
-
-use cvt;
-use crypto::hash::MessageDigest;
-use crypto::symm::Cipher;
-use error::ErrorStack;
-
-#[derive(Clone, Eq, PartialEq, Hash, Debug)]
-pub struct KeyIvPair {
- pub key: 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 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
-/// `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);
- salt.as_ptr()
- }
- None => ptr::null(),
- };
-
- 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 = 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 iv_ptr = iv.as_mut().map(|v| v.as_mut_ptr()).unwrap_or(ptr::null_mut());
-
- 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_ptr)));
-
- Ok(KeyIvPair { key: key, iv: iv })
- }
-}
-
-/// 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,
- key: &mut [u8])
- -> Result<(), ErrorStack> {
- unsafe {
- 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();
- 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(|_| ())
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crypto::hash::MessageDigest;
- use crypto::symm::Cipher;
-
- // Test vectors from
- // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c
- #[test]
- 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 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 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,
- 154_u8, 56_u8, 198_u8, 145_u8, 192_u8, 64_u8, 2_u8, 245_u8, 167_u8, 220_u8,
- 55_u8, 119_u8, 233_u8, 136_u8, 139_u8, 27_u8, 71_u8, 242_u8, 119_u8, 175_u8,
- 65_u8, 207_u8];
-
-
-
- let expected_key = vec![249_u8, 115_u8, 114_u8, 97_u8, 32_u8, 213_u8, 165_u8, 146_u8,
- 58_u8, 87_u8, 234_u8, 3_u8, 43_u8, 250_u8, 97_u8, 114_u8, 26_u8,
- 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];
-
- assert_eq!(super::bytes_to_key(Cipher::aes_256_cbc(),
- MessageDigest::sha1(),
- &data,
- Some(&salt),
- 1).unwrap(),
- super::KeyIvPair {
- key: expected_key,
- iv: Some(expected_iv),
- });
- }
-}
diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs
deleted file mode 100644
index 1d062cfa..00000000
--- a/openssl/src/crypto/pkey.rs
+++ /dev/null
@@ -1,193 +0,0 @@
-use libc::{c_void, c_char, c_int};
-use std::ptr;
-use std::mem;
-use ffi;
-
-use {cvt, cvt_p};
-use bio::{MemBio, MemBioSlice};
-use crypto::dsa::DSA;
-use crypto::rsa::RSA;
-use error::ErrorStack;
-use crypto::util::{CallbackState, invoke_passwd_cb};
-
-pub struct PKey(*mut ffi::EVP_PKEY);
-
-unsafe impl Send for PKey {}
-unsafe impl Sync for PKey {}
-
-/// Represents a public key, optionally with a private key attached.
-impl PKey {
- /// Create 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 pkey = PKey(evp);
- try!(cvt(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_RSA, rsa.as_ptr() as *mut _)));
- mem::forget(rsa);
- Ok(pkey)
- }
- }
-
- /// Create 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 pkey = PKey(evp);
- try!(cvt(ffi::EVP_PKEY_assign(pkey.0, ffi::EVP_PKEY_DSA, dsa.as_ptr() as *mut _)));
- mem::forget(dsa);
- Ok(pkey)
- }
- }
-
- /// Create a new `PKey` containing an HMAC key.
- 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(ffi::EVP_PKEY_HMAC,
- ptr::null_mut(),
- key.as_ptr() as *const _,
- key.len() as c_int)));
- Ok(PKey(key))
- }
- }
-
- pub unsafe fn from_ptr(handle: *mut ffi::EVP_PKEY) -> PKey {
- PKey(handle)
- }
-
- /// Reads private key from PEM, takes ownership of handle
- pub fn private_key_from_pem(buf: &[u8]) -> Result<PKey, ErrorStack> {
- ffi::init();
- let mem_bio = try!(MemBioSlice::new(buf));
- unsafe {
- 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))
- }
- }
-
- /// Read a private key from PEM, supplying a password callback to be invoked if the private key
- /// is encrypted.
- ///
- /// The callback will be passed the password buffer and should return the number of characters
- /// placed into the buffer.
- pub fn private_key_from_pem_cb<F>(buf: &[u8], pass_cb: F) -> Result<PKey, ErrorStack>
- where F: FnOnce(&mut [c_char]) -> usize
- {
- ffi::init();
- let mut cb = CallbackState::new(pass_cb);
- let mem_bio = try!(MemBioSlice::new(buf));
- unsafe {
- 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))
- }
- }
-
- /// Reads public key from PEM, takes ownership of handle
- pub fn public_key_from_pem(buf: &[u8]) -> Result<PKey, ErrorStack> {
- ffi::init();
- let mem_bio = try!(MemBioSlice::new(buf));
- unsafe {
- 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))
- }
- }
-
- /// assign RSA key to this pkey
- pub fn set_rsa(&mut self, rsa: &RSA) -> Result<(), ErrorStack> {
- unsafe {
- // this needs to be a reference as the set1_RSA ups the reference count
- let rsa_ptr = rsa.as_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 rsa(&self) -> Result<RSA, ErrorStack> {
- unsafe {
- 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))
- }
- }
-
- /// Stores private key as a PEM
- // FIXME: also add password and encryption
- pub fn private_key_to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
- let mem_bio = try!(MemBio::new());
- unsafe {
- try!(cvt(ffi::PEM_write_bio_PrivateKey(mem_bio.as_ptr(),
- self.0,
- ptr::null(),
- ptr::null_mut(),
- -1,
- None,
- ptr::null_mut())));
-
- }
- Ok(mem_bio.get_buf().to_owned())
- }
-
- /// 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!(cvt(ffi::PEM_write_bio_PUBKEY(mem_bio.as_ptr(), self.0)));
- }
- Ok(mem_bio.get_buf().to_owned())
- }
-
- pub fn as_ptr(&self) -> *mut ffi::EVP_PKEY {
- return self.0;
- }
-
- pub fn public_eq(&self, other: &PKey) -> bool {
- unsafe { ffi::EVP_PKEY_cmp(self.0, other.0) == 1 }
- }
-}
-
-impl Drop for PKey {
- fn drop(&mut self) {
- unsafe {
- ffi::EVP_PKEY_free(self.0);
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- #[test]
- fn test_private_key_from_pem() {
- let key = include_bytes!("../../test/key.pem");
- super::PKey::private_key_from_pem(key).unwrap();
- }
-
- #[test]
- fn test_public_key_from_pem() {
- let key = include_bytes!("../../test/key.pem.pub");
- super::PKey::public_key_from_pem(key).unwrap();
- }
-
- #[test]
- fn test_pem() {
- let key = include_bytes!("../../test/key.pem");
- let key = super::PKey::private_key_from_pem(key).unwrap();
-
- let priv_key = key.private_key_to_pem().unwrap();
- let pub_key = key.public_key_to_pem().unwrap();
-
- // As a super-simple verification, just check that the buffers contain
- // the `PRIVATE KEY` or `PUBLIC KEY` strings.
- assert!(priv_key.windows(11).any(|s| s == b"PRIVATE KEY"));
- assert!(pub_key.windows(10).any(|s| s == b"PUBLIC KEY"));
- }
-}
diff --git a/openssl/src/crypto/rand.rs b/openssl/src/crypto/rand.rs
deleted file mode 100644
index c1c49e7b..00000000
--- a/openssl/src/crypto/rand.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-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);
- cvt(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int)).map(|_| ())
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::rand_bytes;
-
- #[test]
- fn test_rand_bytes() {
- let mut buf = [0; 32];
- rand_bytes(&mut buf).unwrap();
- }
-}
diff --git a/openssl/src/crypto/rsa.rs b/openssl/src/crypto/rsa.rs
deleted file mode 100644
index 1b9e0e76..00000000
--- a/openssl/src/crypto/rsa.rs
+++ /dev/null
@@ -1,487 +0,0 @@
-use ffi;
-use std::fmt;
-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;
-use crypto::util::{CallbackState, invoke_passwd_cb};
-
-/// Type of encryption padding to use.
-#[derive(Copy, Clone)]
-pub struct Padding(c_int);
-
-impl Padding {
- pub fn none() -> Padding {
- Padding(ffi::RSA_NO_PADDING)
- }
-
- pub fn pkcs1() -> Padding {
- Padding(ffi::RSA_PKCS1_PADDING)
- }
-
- pub fn pkcs1_oaep() -> Padding {
- Padding(ffi::RSA_PKCS1_OAEP_PADDING)
- }
-}
-
-pub struct RSA(*mut ffi::RSA);
-
-impl Drop for RSA {
- fn drop(&mut self) {
- unsafe {
- ffi::RSA_free(self.0);
- }
- }
-}
-
-impl RSA {
- /// only useful for associating the key material directly with the key, it's safer to use
- /// 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(rsa.0,
- n.as_ptr(),
- e.as_ptr(),
- ptr::null_mut())));
- mem::forget((n, e));
- Ok(rsa)
- }
- }
-
- pub fn from_private_components(n: BigNum,
- e: BigNum,
- d: BigNum,
- p: BigNum,
- q: BigNum,
- dp: BigNum,
- dq: BigNum,
- qi: BigNum)
- -> Result<RSA, ErrorStack> {
- unsafe {
- 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!(cvt(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr())));
- mem::forget((p, q));
- try!(cvt(compat::set_crt_params(rsa.0, dp.as_ptr(), dq.as_ptr(),
- qi.as_ptr())));
- mem::forget((dp, dq, qi));
- Ok(rsa)
- }
- }
-
- pub unsafe fn from_ptr(rsa: *mut ffi::RSA) -> RSA {
- RSA(rsa)
- }
-
- /// Generates a public/private key pair with the specified size.
- ///
- /// The public exponent will be 65537.
- pub fn generate(bits: u32) -> Result<RSA, ErrorStack> {
- 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(rsa.0, bits as c_int, e.as_ptr(), ptr::null_mut())));
- Ok(rsa)
- }
- }
-
- /// Reads an RSA private key from PEM formatted data.
- pub fn private_key_from_pem(buf: &[u8]) -> Result<RSA, ErrorStack> {
- let mem_bio = try!(MemBioSlice::new(buf));
- unsafe {
- let rsa = try!(cvt_p(ffi::PEM_read_bio_RSAPrivateKey(mem_bio.as_ptr(),
- ptr::null_mut(),
- None,
- ptr::null_mut())));
- Ok(RSA(rsa))
- }
- }
-
- /// Reads an RSA private key from PEM formatted data and supplies a password callback.
- pub fn private_key_from_pem_cb<F>(buf: &[u8], pass_cb: F) -> Result<RSA, ErrorStack>
- where F: FnOnce(&mut [c_char]) -> usize
- {
- let mut cb = CallbackState::new(pass_cb);
- let mem_bio = try!(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(mem_bio.as_ptr(),
- ptr::null_mut(),
- Some(invoke_passwd_cb::<F>),
- cb_ptr)));
- Ok(RSA(rsa))
- }
- }
-
- /// Reads an RSA public key from PEM formatted data.
- pub fn public_key_from_pem(buf: &[u8]) -> Result<RSA, ErrorStack> {
- let mem_bio = try!(MemBioSlice::new(buf));
- unsafe {
- 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))
- }
- }
-
- /// Writes an RSA private key as unencrypted PEM formatted data
- pub fn private_key_to_pem(&self) -> Result<Vec<u8>, ErrorStack> {
- let mem_bio = try!(MemBio::new());
-
- unsafe {
- 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())
- }
-
- /// Writes an RSA 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!(cvt(ffi::PEM_write_bio_RSA_PUBKEY(mem_bio.as_ptr(), self.0)));
- }
-
- Ok(mem_bio.get_buf().to_owned())
- }
-
- pub fn size(&self) -> usize {
- unsafe {
- assert!(self.n().is_some());
-
- ffi::RSA_size(self.0) as usize
- }
- }
-
- /// 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");
- assert!(from.len() <= i32::max_value() as usize);
- assert!(to.len() >= self.size());
-
- unsafe {
- 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 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");
- assert!(from.len() <= i32::max_value() as usize);
- assert!(to.len() >= self.size());
-
- unsafe {
- 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 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 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 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 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)
- }
- }
-
- pub fn as_ptr(&self) -> *mut ffi::RSA {
- self.0
- }
-
- pub fn n(&self) -> Option<&BigNumRef> {
- unsafe {
- let n = compat::key(self.0)[0];
- if n.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(n as *mut _))
- }
- }
- }
-
- pub fn d(&self) -> Option<&BigNumRef> {
- unsafe {
- let d = compat::key(self.0)[2];
- if d.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(d as *mut _))
- }
- }
- }
-
- pub fn e(&self) -> Option<&BigNumRef> {
- unsafe {
- let e = compat::key(self.0)[1];
- if e.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(e as *mut _))
- }
- }
- }
-
- pub fn p(&self) -> Option<&BigNumRef> {
- unsafe {
- let p = compat::factors(self.0)[0];
- if p.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(p as *mut _))
- }
- }
- }
-
- pub fn q(&self) -> Option<&BigNumRef> {
- unsafe {
- let q = compat::factors(self.0)[1];
- if q.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(q as *mut _))
- }
- }
- }
-}
-
-impl fmt::Debug for RSA {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "RSA")
- }
-}
-
-#[cfg(ossl110)]
-mod compat {
- use std::ptr;
-
- use ffi::{self, BIGNUM, RSA};
- use libc::c_int;
-
- pub unsafe fn key(r: *const RSA) -> [*const BIGNUM; 3] {
- let (mut n, mut e, mut d) = (ptr::null(), ptr::null(), ptr::null());
- ffi::RSA_get0_key(r, &mut n, &mut e, &mut d);
- [n, e, d]
- }
-
- pub unsafe fn factors(r: *const RSA) -> [*const BIGNUM; 2] {
- let (mut p, mut q) = (ptr::null(), ptr::null());
- ffi::RSA_get0_factors(r, &mut p, &mut q);
- [p, q]
- }
-
- pub unsafe fn set_key(r: *mut RSA,
- n: *mut BIGNUM,
- e: *mut BIGNUM,
- d: *mut BIGNUM) -> c_int {
- ffi::RSA_set0_key(r, n, e, d)
- }
-
- pub unsafe fn set_factors(r: *mut RSA,
- p: *mut BIGNUM,
- q: *mut BIGNUM) -> c_int {
- ffi::RSA_set0_factors(r, p, q)
- }
-
- pub unsafe fn set_crt_params(r: *mut RSA,
- dmp1: *mut BIGNUM,
- dmq1: *mut BIGNUM,
- iqmp: *mut BIGNUM) -> c_int {
- ffi::RSA_set0_crt_params(r, dmp1, dmq1, iqmp)
- }
-}
-
-#[cfg(ossl10x)]
-mod compat {
- use libc::c_int;
- use ffi::{BIGNUM, RSA};
-
- pub unsafe fn key(r: *const RSA) -> [*const BIGNUM; 3] {
- [(*r).n, (*r).e, (*r).d]
- }
-
- pub unsafe fn factors(r: *const RSA) -> [*const BIGNUM; 2] {
- [(*r).p, (*r).q]
- }
-
- pub unsafe fn set_key(r: *mut RSA,
- n: *mut BIGNUM,
- e: *mut BIGNUM,
- d: *mut BIGNUM) -> c_int {
- (*r).n = n;
- (*r).e = e;
- (*r).d = d;
- 1 // TODO: is this right? should it be 0? what's success?
- }
-
- pub unsafe fn set_factors(r: *mut RSA,
- p: *mut BIGNUM,
- q: *mut BIGNUM) -> c_int {
- (*r).p = p;
- (*r).q = q;
- 1 // TODO: is this right? should it be 0? what's success?
- }
-
- pub unsafe fn set_crt_params(r: *mut RSA,
- dmp1: *mut BIGNUM,
- dmq1: *mut BIGNUM,
- iqmp: *mut BIGNUM) -> c_int {
- (*r).dmp1 = dmp1;
- (*r).dmq1 = dmq1;
- (*r).iqmp = iqmp;
- 1 // TODO: is this right? should it be 0? what's success?
- }
-}
-
-
-#[cfg(test)]
-mod test {
- use libc::c_char;
-
- use super::*;
-
- #[test]
- pub fn test_password() {
- let mut password_queried = false;
- let key = include_bytes!("../../test/rsa-encrypted.pem");
- RSA::private_key_from_pem_cb(key, |password| {
- password_queried = true;
- password[0] = b'm' as c_char;
- password[1] = b'y' as c_char;
- password[2] = b'p' as c_char;
- password[3] = b'a' as c_char;
- password[4] = b's' as c_char;
- password[5] = b's' as c_char;
- 6
- }).unwrap();
-
- assert!(password_queried);
- }
-
- #[test]
- pub fn test_public_encrypt_private_decrypt_with_padding() {
- let key = include_bytes!("../../test/rsa.pem.pub");
- let public_key = RSA::public_key_from_pem(key).unwrap();
-
- 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 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[..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 msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
-
- 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.private_key_to_pem().unwrap();
- let k1 = super::RSA::private_key_from_pem(&k0pkey).unwrap();
-
- let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
-
- 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
deleted file mode 100644
index 41009149..00000000
--- a/openssl/src/crypto/sign.rs
+++ /dev/null
@@ -1,397 +0,0 @@
-//! Message signatures.
-//!
-//! The `Signer` allows for the computation of cryptographic signatures of
-//! data given a private key. The `Verifier` can then be used with the
-//! corresponding public key to verify the integrity and authenticity of that
-//! data given the signature.
-//!
-//! # Examples
-//!
-//! Sign and verify data given an RSA keypair:
-//!
-//! ```rust
-//! use openssl::crypto::sign::{Signer, Verifier};
-//! use openssl::crypto::rsa::RSA;
-//! use openssl::crypto::pkey::PKey;
-//! use openssl::crypto::hash::MessageDigest;
-//!
-//! // Generate a keypair
-//! let keypair = RSA::generate(2048).unwrap();
-//! let keypair = PKey::from_rsa(keypair).unwrap();
-//!
-//! let data = b"hello, world!";
-//! let data2 = b"hola, mundo!";
-//!
-//! // Sign the data
-//! let mut signer = Signer::new(MessageDigest::sha256(), &keypair).unwrap();
-//! signer.update(data).unwrap();
-//! signer.update(data2).unwrap();
-//! let signature = signer.finish().unwrap();
-//!
-//! // Verify the data
-//! let mut verifier = Verifier::new(MessageDigest::sha256(), &keypair).unwrap();
-//! verifier.update(data).unwrap();
-//! verifier.update(data2).unwrap();
-//! assert!(verifier.finish(&signature).unwrap());
-//! ```
-//!
-//! Compute an HMAC (note that `Verifier` cannot be used with HMACs):
-//!
-//! ```rust
-//! use openssl::crypto::sign::Signer;
-//! use openssl::crypto::pkey::PKey;
-//! use openssl::crypto::hash::MessageDigest;
-//!
-//! // Create a PKey
-//! let key = PKey::hmac(b"my secret").unwrap();
-//!
-//! let data = b"hello, world!";
-//! let data2 = b"hola, mundo!";
-//!
-//! // Compute the HMAC
-//! let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap();
-//! signer.update(data).unwrap();
-//! signer.update(data2).unwrap();
-//! let hmac = signer.finish().unwrap();
-//! ```
-use ffi;
-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;
-
-#[cfg(ossl110)]
-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};
-
-pub struct Signer<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a PKey>);
-
-impl<'a> Drop for Signer<'a> {
- fn drop(&mut self) {
- unsafe {
- EVP_MD_CTX_free(self.0);
- }
- }
-}
-
-impl<'a> Signer<'a> {
- pub fn new(type_: MessageDigest, pkey: &'a PKey) -> Result<Signer<'a>, ErrorStack> {
- unsafe {
- ffi::init();
-
- let ctx = try!(cvt_p(EVP_MD_CTX_new()));
- let r = ffi::EVP_DigestSignInit(ctx,
- ptr::null_mut(),
- type_.as_ptr(),
- ptr::null_mut(),
- pkey.as_ptr());
- if r != 1 {
- EVP_MD_CTX_free(ctx);
- return Err(ErrorStack::get());
- }
- Ok(Signer(ctx, PhantomData))
- }
- }
-
- pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> {
- unsafe {
- 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!(cvt(ffi::EVP_DigestSignFinal(self.0, ptr::null_mut(), &mut len)));
- let mut buf = vec![0; len];
- 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)
- }
- }
-}
-
-impl<'a> Write for Signer<'a> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- try!(self.update(buf));
- Ok(buf.len())
- }
-
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
-}
-
-pub struct Verifier<'a>(*mut ffi::EVP_MD_CTX, PhantomData<&'a PKey>);
-
-impl<'a> Drop for Verifier<'a> {
- fn drop(&mut self) {
- unsafe {
- EVP_MD_CTX_free(self.0);
- }
- }
-}
-
-impl<'a> Verifier<'a> {
- pub fn new(type_: MessageDigest, pkey: &'a PKey) -> Result<Verifier<'a>, ErrorStack> {
- unsafe {
- ffi::init();
-
- let ctx = try!(cvt_p(EVP_MD_CTX_new()));
- let r = ffi::EVP_DigestVerifyInit(ctx,
- ptr::null_mut(),
- type_.as_ptr(),
- ptr::null_mut(),
- pkey.as_ptr());
- if r != 1 {
- EVP_MD_CTX_free(ctx);
- return Err(ErrorStack::get());
- }
-
- Ok(Verifier(ctx, PhantomData))
- }
- }
-
- pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> {
- unsafe {
- cvt(ffi::EVP_DigestUpdate(self.0, buf.as_ptr() as *const _, buf.len())).map(|_| ())
- }
- }
-
- pub fn finish(&self, signature: &[u8]) -> Result<bool, ErrorStack> {
- unsafe {
- let r = EVP_DigestVerifyFinal(self.0,
- signature.as_ptr() as *const _,
- signature.len());
- match r {
- 1 => Ok(true),
- 0 => {
- ErrorStack::get(); // discard error stack
- Ok(false)
- }
- _ => Err(ErrorStack::get()),
- }
- }
- }
-}
-
-impl<'a> Write for Verifier<'a> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- try!(self.update(buf));
- Ok(buf.len())
- }
-
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
-}
-
-#[cfg(not(ossl101))]
-use ffi::EVP_DigestVerifyFinal;
-
-#[cfg(ossl101)]
-#[allow(bad_style)]
-unsafe fn EVP_DigestVerifyFinal(ctx: *mut ffi::EVP_MD_CTX,
- sigret: *const ::libc::c_uchar,
- siglen: ::libc::size_t) -> ::libc::c_int {
- ffi::EVP_DigestVerifyFinal(ctx, sigret as *mut _, siglen)
-}
-
-#[cfg(test)]
-mod test {
- use serialize::hex::FromHex;
- use std::iter;
-
- use crypto::hash::MessageDigest;
- use crypto::sign::{Signer, Verifier};
- use crypto::rsa::RSA;
- use crypto::dsa::DSA;
- use crypto::pkey::PKey;
-
- static INPUT: &'static [u8] =
- &[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];
-
- static SIGNATURE: &'static [u8] =
- &[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]
- fn rsa_sign() {
- let key = include_bytes!("../../test/rsa.pem");
- let private_key = RSA::private_key_from_pem(key).unwrap();
- let pkey = PKey::from_rsa(private_key).unwrap();
-
- let mut signer = Signer::new(MessageDigest::sha256(), &pkey).unwrap();
- signer.update(INPUT).unwrap();
- let result = signer.finish().unwrap();
-
- assert_eq!(result, SIGNATURE);
- }
-
- #[test]
- fn rsa_verify_ok() {
- let key = include_bytes!("../../test/rsa.pem");
- let private_key = RSA::private_key_from_pem(key).unwrap();
- let pkey = PKey::from_rsa(private_key).unwrap();
-
- let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap();
- verifier.update(INPUT).unwrap();
- assert!(verifier.finish(SIGNATURE).unwrap());
- }
-
- #[test]
- fn rsa_verify_invalid() {
- let key = include_bytes!("../../test/rsa.pem");
- let private_key = RSA::private_key_from_pem(key).unwrap();
- let pkey = PKey::from_rsa(private_key).unwrap();
-
- let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap();
- verifier.update(INPUT).unwrap();
- verifier.update(b"foobar").unwrap();
- assert!(!verifier.finish(SIGNATURE).unwrap());
- }
-
- #[test]
- pub fn dsa_sign_verify() {
- let input: Vec<u8> = (0..25).cycle().take(1024).collect();
-
- let private_key = {
- let key = include_bytes!("../../test/dsa.pem");
- PKey::from_dsa(DSA::private_key_from_pem(key).unwrap()).unwrap()
- };
-
- let public_key = {
- let key = include_bytes!("../../test/dsa.pem.pub");
- PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap()
- };
-
- let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap();
- signer.update(&input).unwrap();
- let sig = signer.finish().unwrap();
-
- let mut verifier = Verifier::new(MessageDigest::sha1(), &public_key).unwrap();
- verifier.update(&input).unwrap();
- assert!(verifier.finish(&sig).unwrap());
- }
-
- #[test]
- pub fn dsa_sign_verify_fail() {
- let input: Vec<u8> = (0..25).cycle().take(1024).collect();
-
- let private_key = {
- let key = include_bytes!("../../test/dsa.pem");
- PKey::from_dsa(DSA::private_key_from_pem(key).unwrap()).unwrap()
- };
-
- let public_key = {
- let key = include_bytes!("../../test/dsa.pem.pub");
- PKey::from_dsa(DSA::public_key_from_pem(key).unwrap()).unwrap()
- };
-
- let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap();
- signer.update(&input).unwrap();
- let mut sig = signer.finish().unwrap();
- sig[0] -= 1;
-
- let mut verifier = Verifier::new(MessageDigest::sha1(), &public_key).unwrap();
- verifier.update(&input).unwrap();
- match verifier.finish(&sig) {
- Ok(true) => panic!("unexpected success"),
- Ok(false) | Err(_) => {},
- }
- }
-
- fn test_hmac(ty: MessageDigest, tests: &[(Vec<u8>, Vec<u8>, Vec<u8>)]) {
- for &(ref key, ref data, ref res) in tests.iter() {
- let pkey = PKey::hmac(key).unwrap();
- let mut signer = Signer::new(ty, &pkey).unwrap();
- signer.update(data).unwrap();
- assert_eq!(signer.finish().unwrap(), *res);
- }
- }
-
- #[test]
- fn hmac_md5() {
- // test vectors from RFC 2202
- let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 7] =
- [(iter::repeat(0x0b_u8).take(16).collect(),
- b"Hi There".to_vec(),
- "9294727a3638bb1c13f48ef8158bfc9d".from_hex().unwrap()),
- (b"Jefe".to_vec(),
- b"what do ya want for nothing?".to_vec(),
- "750c783e6ab0b503eaa86e310a5db738".from_hex().unwrap()),
- (iter::repeat(0xaa_u8).take(16).collect(),
- iter::repeat(0xdd_u8).take(50).collect(),
- "56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()),
- ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
- iter::repeat(0xcd_u8).take(50).collect(),
- "697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()),
- (iter::repeat(0x0c_u8).take(16).collect(),
- b"Test With Truncation".to_vec(),
- "56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()),
- (iter::repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
- "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
- (iter::repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key \
- and Larger Than One Block-Size Data"
- .to_vec(),
- "6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())];
-
- test_hmac(MessageDigest::md5(), &tests);
- }
-
- #[test]
- fn hmac_sha1() {
- // test vectors from RFC 2202
- let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 7] =
- [(iter::repeat(0x0b_u8).take(20).collect(),
- b"Hi There".to_vec(),
- "b617318655057264e28bc0b6fb378c8ef146be00".from_hex().unwrap()),
- (b"Jefe".to_vec(),
- b"what do ya want for nothing?".to_vec(),
- "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".from_hex().unwrap()),
- (iter::repeat(0xaa_u8).take(20).collect(),
- iter::repeat(0xdd_u8).take(50).collect(),
- "125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()),
- ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
- iter::repeat(0xcd_u8).take(50).collect(),
- "4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()),
- (iter::repeat(0x0c_u8).take(20).collect(),
- b"Test With Truncation".to_vec(),
- "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()),
- (iter::repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
- "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()),
- (iter::repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key \
- and Larger Than One Block-Size Data"
- .to_vec(),
- "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())];
-
- test_hmac(MessageDigest::sha1(), &tests);
- }
-}
diff --git a/openssl/src/crypto/symm.rs b/openssl/src/crypto/symm.rs
deleted file mode 100644
index 65f0addb..00000000
--- a/openssl/src/crypto/symm.rs
+++ /dev/null
@@ -1,558 +0,0 @@
-use std::cmp;
-use std::ptr;
-use libc::c_int;
-use ffi;
-
-use {cvt, cvt_p};
-use error::ErrorStack;
-
-#[derive(Copy, Clone)]
-pub enum Mode {
- Encrypt,
- Decrypt,
-}
-
-#[derive(Copy, Clone)]
-pub struct Cipher(*const ffi::EVP_CIPHER);
-
-impl Cipher {
- pub fn aes_128_ecb() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_128_ecb())
- }
- }
-
- pub fn aes_128_cbc() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_128_cbc())
- }
- }
-
- pub fn aes_128_xts() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_128_xts())
- }
- }
-
- pub fn aes_128_ctr() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_128_ctr())
- }
- }
-
- pub fn aes_128_cfb1() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_128_cfb1())
- }
- }
-
- pub fn aes_128_cfb128() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_128_cfb128())
- }
- }
-
- pub fn aes_128_cfb8() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_128_cfb8())
- }
- }
-
- pub fn aes_256_ecb() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_256_ecb())
- }
- }
-
- pub fn aes_256_cbc() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_256_cbc())
- }
- }
-
- pub fn aes_256_xts() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_256_xts())
- }
- }
-
- pub fn aes_256_ctr() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_256_ctr())
- }
- }
-
- pub fn aes_256_cfb1() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_256_cfb1())
- }
- }
-
- pub fn aes_256_cfb128() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_256_cfb128())
- }
- }
-
- pub fn aes_256_cfb8() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_aes_256_cfb8())
- }
- }
-
- pub fn des_cbc() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_des_cbc())
- }
- }
-
- pub fn des_ecb() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_des_ecb())
- }
- }
-
- pub fn rc4() -> Cipher {
- unsafe {
- Cipher(ffi::EVP_rc4())
- }
- }
-
- pub fn as_ptr(&self) -> *const ffi::EVP_CIPHER {
- self.0
- }
-
- /// Returns the length of keys used with this cipher.
- pub fn key_len(&self) -> usize {
- unsafe {
- EVP_CIPHER_key_length(self.0) as usize
- }
- }
-
- /// Returns the length of the IV used with this cipher, or `None` if the
- /// cipher does not use an IV.
- pub fn iv_len(&self) -> Option<usize> {
- unsafe {
- let len = EVP_CIPHER_iv_length(self.0) as usize;
- if len == 0 {
- None
- } else {
- Some(len)
- }
- }
- }
-
- /// Returns the block size of the cipher.
- ///
- /// # Note
- ///
- /// Stream ciphers such as RC4 have a block size of 1.
- pub fn block_size(&self) -> usize {
- unsafe {
- EVP_CIPHER_block_size(self.0) as usize
- }
- }
-}
-
-/// Represents a symmetric cipher context.
-pub struct Crypter {
- ctx: *mut ffi::EVP_CIPHER_CTX,
- block_size: usize,
-}
-
-impl Crypter {
- /// Creates a new `Crypter`.
- ///
- /// # Panics
- ///
- /// Panics if an IV is required by the cipher but not provided, or if the
- /// IV's length does not match the expected length (see `Cipher::iv_len`).
- pub fn new(t: Cipher, mode: Mode, key: &[u8], iv: Option<&[u8]>) -> Result<Crypter, ErrorStack> {
- ffi::init();
-
- unsafe {
- let ctx = try!(cvt_p(ffi::EVP_CIPHER_CTX_new()));
- let crypter = Crypter {
- ctx: ctx,
- block_size: t.block_size(),
- };
-
- let mode = match mode {
- Mode::Encrypt => 1,
- Mode::Decrypt => 0,
- };
-
- 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!(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)) => {
- assert!(iv.len() == len);
- 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(crypter.ctx,
- ptr::null(),
- ptr::null_mut(),
- key,
- iv,
- mode)));
-
- Ok(crypter)
- }
- }
-
- /// Enables or disables padding.
- ///
- /// If padding is disabled, total amount of data encrypted/decrypted must
- /// be a multiple of the cipher's block size.
- pub fn pad(&mut self, padding: bool) {
- unsafe { ffi::EVP_CIPHER_CTX_set_padding(self.ctx, padding as c_int); }
- }
-
- /// Feeds data from `input` through the cipher, writing encrypted/decrypted
- /// bytes into `output`.
- ///
- /// The number of bytes written to `output` is returned. Note that this may
- /// not be equal to the length of `input`.
- ///
- /// # Panics
- ///
- /// Panics if `output.len() < input.len() + block_size` where
- /// `block_size` is the block size of the cipher (see `Cipher::block_size`),
- /// or if `output.len() > c_int::max_value()`.
- pub fn update(&mut self, input: &[u8], output: &mut [u8]) -> Result<usize, ErrorStack> {
- unsafe {
- assert!(output.len() >= input.len() + self.block_size);
- assert!(output.len() <= c_int::max_value() as usize);
- let mut outl = output.len() as c_int;
- let inl = input.len() as c_int;
-
- try!(cvt(ffi::EVP_CipherUpdate(self.ctx,
- output.as_mut_ptr(),
- &mut outl,
- input.as_ptr(),
- inl)));
-
- Ok(outl as usize)
- }
- }
-
- /// Finishes the encryption/decryption process, writing any remaining data
- /// to `output`.
- ///
- /// The number of bytes written to `output` is returned.
- ///
- /// `update` should not be called after this method.
- ///
- /// # Panics
- ///
- /// Panics if `output` is less than the cipher's block size.
- pub fn finalize(&mut self, output: &mut [u8]) -> Result<usize, ErrorStack> {
- unsafe {
- 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(self.ctx, output.as_mut_ptr(), &mut outl)));
-
- Ok(outl as usize)
- }
- }
-}
-
-impl Drop for Crypter {
- fn drop(&mut self) {
- unsafe {
- ffi::EVP_CIPHER_CTX_free(self.ctx);
- }
- }
-}
-
-/**
- * Encrypts data, using the specified crypter type in encrypt mode with the
- * specified key and iv; returns the resulting (encrypted) data.
- */
-pub fn encrypt(t: Cipher,
- key: &[u8],
- iv: Option<&[u8]>,
- data: &[u8])
- -> Result<Vec<u8>, ErrorStack> {
- cipher(t, Mode::Encrypt, key, iv, data)
-}
-
-/**
- * Decrypts data, using the specified crypter type in decrypt mode with the
- * specified key and iv; returns the resulting (decrypted) data.
- */
-pub fn decrypt(t: Cipher,
- key: &[u8],
- iv: Option<&[u8]>,
- data: &[u8])
- -> Result<Vec<u8>, ErrorStack> {
- cipher(t, Mode::Decrypt, key, iv, data)
-}
-
-fn cipher(t: Cipher,
- mode: Mode,
- key: &[u8],
- iv: Option<&[u8]>,
- data: &[u8])
- -> Result<Vec<u8>, ErrorStack> {
- let mut c = try!(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..]));
- out.truncate(count + rest);
- Ok(out)
-}
-
-#[cfg(ossl110)]
-use ffi::{EVP_CIPHER_iv_length, EVP_CIPHER_block_size, EVP_CIPHER_key_length};
-
-#[cfg(ossl10x)]
-#[allow(bad_style)]
-mod compat {
- use libc::c_int;
- use ffi::EVP_CIPHER;
-
- pub unsafe fn EVP_CIPHER_iv_length(ptr: *const EVP_CIPHER) -> c_int {
- (*ptr).iv_len
- }
-
- pub unsafe fn EVP_CIPHER_block_size(ptr: *const EVP_CIPHER) -> c_int {
- (*ptr).block_size
- }
-
- pub unsafe fn EVP_CIPHER_key_length(ptr: *const EVP_CIPHER) -> c_int {
- (*ptr).key_len
- }
-}
-#[cfg(ossl10x)]
-use self::compat::*;
-
-#[cfg(test)]
-mod tests {
- use serialize::hex::{FromHex, ToHex};
-
- // Test vectors from FIPS-197:
- // http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
- #[test]
- fn test_aes_256_ecb() {
- let k0 = [0x00u8, 0x01u8, 0x02u8, 0x03u8, 0x04u8, 0x05u8, 0x06u8, 0x07u8, 0x08u8, 0x09u8,
- 0x0au8, 0x0bu8, 0x0cu8, 0x0du8, 0x0eu8, 0x0fu8, 0x10u8, 0x11u8, 0x12u8, 0x13u8,
- 0x14u8, 0x15u8, 0x16u8, 0x17u8, 0x18u8, 0x19u8, 0x1au8, 0x1bu8, 0x1cu8, 0x1du8,
- 0x1eu8, 0x1fu8];
- let p0 = [0x00u8, 0x11u8, 0x22u8, 0x33u8, 0x44u8, 0x55u8, 0x66u8, 0x77u8, 0x88u8, 0x99u8,
- 0xaau8, 0xbbu8, 0xccu8, 0xddu8, 0xeeu8, 0xffu8];
- let c0 = [0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8, 0xeau8, 0xfcu8,
- 0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8];
- let mut c = super::Crypter::new(super::Cipher::aes_256_ecb(),
- super::Mode::Encrypt,
- &k0,
- None).unwrap();
- c.pad(false);
- let mut r0 = vec![0; c0.len() + super::Cipher::aes_256_ecb().block_size()];
- let count = c.update(&p0, &mut r0).unwrap();
- let rest = c.finalize(&mut r0[count..]).unwrap();
- r0.truncate(count + rest);
- assert_eq!(r0.to_hex(), c0.to_hex());
-
- let mut c = super::Crypter::new(super::Cipher::aes_256_ecb(),
- super::Mode::Decrypt,
- &k0,
- None).unwrap();
- c.pad(false);
- let mut p1 = vec![0; r0.len() + super::Cipher::aes_256_ecb().block_size()];
- let count = c.update(&r0, &mut p1).unwrap();
- let rest = c.finalize(&mut p1[count..]).unwrap();
- p1.truncate(count + rest);
- assert_eq!(p1.to_hex(), p0.to_hex());
- }
-
- #[test]
- fn test_aes_256_cbc_decrypt() {
- let iv = [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];
- let data = [143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8, 241_u8, 242_u8, 31_u8,
- 154_u8, 56_u8, 198_u8, 145_u8, 192_u8, 64_u8, 2_u8, 245_u8, 167_u8, 220_u8,
- 55_u8, 119_u8, 233_u8, 136_u8, 139_u8, 27_u8, 71_u8, 242_u8, 119_u8, 175_u8,
- 65_u8, 207_u8];
- let ciphered_data = [0x4a_u8, 0x2e_u8, 0xe5_u8, 0x6_u8, 0xbf_u8, 0xcf_u8, 0xf2_u8,
- 0xd7_u8, 0xea_u8, 0x2d_u8, 0xb1_u8, 0x85_u8, 0x6c_u8, 0x93_u8,
- 0x65_u8, 0x6f_u8];
- let mut cr = super::Crypter::new(super::Cipher::aes_256_cbc(),
- super::Mode::Decrypt,
- &data,
- Some(&iv)).unwrap();
- cr.pad(false);
- let mut unciphered_data = vec![0; data.len() + super::Cipher::aes_256_cbc().block_size()];
- let count = cr.update(&ciphered_data, &mut unciphered_data).unwrap();
- let rest = cr.finalize(&mut unciphered_data[count..]).unwrap();
- unciphered_data.truncate(count + rest);
-
- let expected_unciphered_data = b"I love turtles.\x01";
-
- assert_eq!(&unciphered_data, expected_unciphered_data);
- }
-
- fn cipher_test(ciphertype: super::Cipher, pt: &str, ct: &str, key: &str, iv: &str) {
- use serialize::hex::ToHex;
-
- let pt = pt.from_hex().unwrap();
- let ct = ct.from_hex().unwrap();
- let key = key.from_hex().unwrap();
- let iv = iv.from_hex().unwrap();
-
- let computed = super::decrypt(ciphertype, &key, Some(&iv), &ct).unwrap();
- let expected = pt;
-
- if computed != expected {
- println!("Computed: {}", computed.to_hex());
- println!("Expected: {}", expected.to_hex());
- if computed.len() != expected.len() {
- println!("Lengths differ: {} in computed vs {} expected",
- computed.len(),
- expected.len());
- }
- panic!("test failure");
- }
- }
-
- #[test]
- fn test_rc4() {
-
- let pt = "0000000000000000000000000000000000000000000000000000000000000000000000000000";
- let ct = "A68686B04D686AA107BD8D4CAB191A3EEC0A6294BC78B60F65C25CB47BD7BB3A48EFC4D26BE4";
- let key = "97CD440324DA5FD1F7955C1C13B6B466";
- let iv = "";
-
- cipher_test(super::Cipher::rc4(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_aes256_xts() {
- // Test case 174 from
- // http://csrc.nist.gov/groups/STM/cavp/documents/aes/XTSTestVectors.zip
- let pt = "77f4ef63d734ebd028508da66c22cdebdd52ecd6ee2ab0a50bc8ad0cfd692ca5fcd4e6dedc45df7f\
- 6503f462611dc542";
- let ct = "ce7d905a7776ac72f240d22aafed5e4eb7566cdc7211220e970da634ce015f131a5ecb8d400bc9e8\
- 4f0b81d8725dbbc7";
- let key = "b6bfef891f83b5ff073f2231267be51eb084b791fa19a154399c0684c8b2dfcb37de77d28bbda3b\
- 4180026ad640b74243b3133e7b9fae629403f6733423dae28";
- let iv = "db200efb7eaaa737dbdf40babb68953f";
-
- cipher_test(super::Cipher::aes_256_xts(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_aes128_ctr() {
-
- let pt = "6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411\
- E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710";
- let ct = "874D6191B620E3261BEF6864990DB6CE9806F66B7970FDFF8617187BB9FFFDFF5AE4DF3EDBD5D35E\
- 5B4F09020DB03EAB1E031DDA2FBE03D1792170A0F3009CEE";
- let key = "2B7E151628AED2A6ABF7158809CF4F3C";
- let iv = "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
-
- cipher_test(super::Cipher::aes_128_ctr(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_aes128_cfb1() {
- // Lifted from http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
-
- let pt = "6bc1";
- let ct = "68b3";
- let key = "2b7e151628aed2a6abf7158809cf4f3c";
- let iv = "000102030405060708090a0b0c0d0e0f";
-
- cipher_test(super::Cipher::aes_128_cfb1(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_aes128_cfb128() {
-
- let pt = "6bc1bee22e409f96e93d7e117393172a";
- let ct = "3b3fd92eb72dad20333449f8e83cfb4a";
- let key = "2b7e151628aed2a6abf7158809cf4f3c";
- let iv = "000102030405060708090a0b0c0d0e0f";
-
- cipher_test(super::Cipher::aes_128_cfb128(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_aes128_cfb8() {
-
- let pt = "6bc1bee22e409f96e93d7e117393172aae2d";
- let ct = "3b79424c9c0dd436bace9e0ed4586a4f32b9";
- let key = "2b7e151628aed2a6abf7158809cf4f3c";
- let iv = "000102030405060708090a0b0c0d0e0f";
-
- cipher_test(super::Cipher::aes_128_cfb8(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_aes256_cfb1() {
-
- let pt = "6bc1";
- let ct = "9029";
- let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4";
- let iv = "000102030405060708090a0b0c0d0e0f";
-
- cipher_test(super::Cipher::aes_256_cfb1(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_aes256_cfb128() {
-
- let pt = "6bc1bee22e409f96e93d7e117393172a";
- let ct = "dc7e84bfda79164b7ecd8486985d3860";
- let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4";
- let iv = "000102030405060708090a0b0c0d0e0f";
-
- cipher_test(super::Cipher::aes_256_cfb128(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_aes256_cfb8() {
-
- let pt = "6bc1bee22e409f96e93d7e117393172aae2d";
- let ct = "dc1f1a8520a64db55fcc8ac554844e889700";
- let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4";
- let iv = "000102030405060708090a0b0c0d0e0f";
-
- cipher_test(super::Cipher::aes_256_cfb8(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_des_cbc() {
-
- let pt = "54686973206973206120746573742e";
- let ct = "6f2867cfefda048a4046ef7e556c7132";
- let key = "7cb66337f3d3c0fe";
- let iv = "0001020304050607";
-
- cipher_test(super::Cipher::des_cbc(), pt, ct, key, iv);
- }
-
- #[test]
- fn test_des_ecb() {
-
- let pt = "54686973206973206120746573742e";
- let ct = "0050ab8aecec758843fe157b4dde938c";
- let key = "7cb66337f3d3c0fe";
- let iv = "0001020304050607";
-
- cipher_test(super::Cipher::des_ecb(), pt, ct, key, iv);
- }
-}
diff --git a/openssl/src/crypto/util.rs b/openssl/src/crypto/util.rs
deleted file mode 100644
index 68d9b32a..00000000
--- a/openssl/src/crypto/util.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-use libc::{c_int, c_char, c_void};
-
-use std::any::Any;
-use std::panic::{self, AssertUnwindSafe};
-use std::slice;
-
-/// Wraps a user-supplied callback and a slot for panics thrown inside the callback (while FFI
-/// frames are on the stack).
-///
-/// When dropped, checks if the callback has panicked, and resumes unwinding if so.
-pub struct CallbackState<F> {
- /// The user callback. Taken out of the `Option` when called.
- cb: Option<F>,
- /// If the callback panics, we place the panic object here, to be re-thrown once OpenSSL
- /// returns.
- panic: Option<Box<Any + Send + 'static>>,
-}
-
-impl<F> CallbackState<F> {
- pub fn new(callback: F) -> Self {
- CallbackState {
- cb: Some(callback),
- panic: None,
- }
- }
-}
-
-impl<F> Drop for CallbackState<F> {
- fn drop(&mut self) {
- if let Some(panic) = self.panic.take() {
- panic::resume_unwind(panic);
- }
- }
-}
-
-/// Password callback function, passed to private key loading functions.
-///
-/// `cb_state` is expected to be a pointer to a `CallbackState`.
-pub unsafe extern fn invoke_passwd_cb<F>(buf: *mut c_char,
- size: c_int,
- _rwflag: c_int,
- cb_state: *mut c_void)
- -> c_int
- where F: FnOnce(&mut [c_char]) -> usize {
- let callback = &mut *(cb_state as *mut CallbackState<F>);
-
- let result = panic::catch_unwind(AssertUnwindSafe(|| {
- // build a `i8` slice to pass to the user callback
- let pass_slice = slice::from_raw_parts_mut(buf, size as usize);
-
- callback.cb.take().unwrap()(pass_slice)
- }));
-
- match result {
- Ok(len) => len as c_int,
- Err(err) => {
- callback.panic = Some(err);
- 0
- }
- }
-}