aboutsummaryrefslogtreecommitdiff
path: root/openssl/src/crypto
diff options
context:
space:
mode:
authorSteven Fackler <[email protected]>2016-11-05 20:06:50 -0700
committerSteven Fackler <[email protected]>2016-11-05 20:06:50 -0700
commita0b56c437803a08413755928040a0970a93a7b83 (patch)
tree0f21848301b62d6078eafaee10e513df4163087b /openssl/src/crypto
parentMerge branch 'release-v0.8.3' into release (diff)
parentRelease v0.9.0 (diff)
downloadrust-openssl-0.9.0.tar.xz
rust-openssl-0.9.0.zip
Merge branch 'release-v0.9.0' into releasev0.9.0
Diffstat (limited to 'openssl/src/crypto')
-rw-r--r--openssl/src/crypto/dsa.rs338
-rw-r--r--openssl/src/crypto/hash.rs339
-rw-r--r--openssl/src/crypto/hmac.rs511
-rw-r--r--openssl/src/crypto/memcmp.rs39
-rw-r--r--openssl/src/crypto/mod.rs28
-rw-r--r--openssl/src/crypto/pkcs12.rs92
-rw-r--r--openssl/src/crypto/pkcs5.rs245
-rw-r--r--openssl/src/crypto/pkey.rs166
-rw-r--r--openssl/src/crypto/rand.rs23
-rw-r--r--openssl/src/crypto/rsa.rs337
-rw-r--r--openssl/src/crypto/symm.rs503
-rw-r--r--openssl/src/crypto/util.rs58
12 files changed, 0 insertions, 2679 deletions
diff --git a/openssl/src/crypto/dsa.rs b/openssl/src/crypto/dsa.rs
deleted file mode 100644
index 97ba7a97..00000000
--- a/openssl/src/crypto/dsa.rs
+++ /dev/null
@@ -1,338 +0,0 @@
-use ffi;
-use std::fmt;
-use error::ErrorStack;
-use std::ptr;
-use libc::{c_uint, c_int, c_char, c_void};
-
-use bn::BigNumRef;
-use bio::{MemBio, MemBioSlice};
-use crypto::hash;
-use HashTypeInternals;
-use crypto::util::{CallbackState, invoke_passwd_cb};
-
-
-/// Builder for upfront DSA parameter generateration
-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, size as c_int, ptr::null(), 0,
- ptr::null_mut(), ptr::null_mut(), ptr::null()));
- Ok(dsa)
- }
- }
-
- /// Generate a key pair from the initialized parameters
- pub fn generate(self) -> Result<DSA, ErrorStack> {
- unsafe {
- try_ssl!(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_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)
- }
- }
-
- /// 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_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)
- }
- }
-
- /// 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_ssl!(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_ssl_null!(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_ssl!(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 sign(&self, hash: hash::Type, message: &[u8]) -> Result<Vec<u8>, ErrorStack> {
- let k_len = self.size().expect("DSA missing a q") as c_uint;
- let mut sig = vec![0; k_len as usize];
- let mut sig_len = k_len;
- assert!(self.has_private_key());
-
- unsafe {
- try_ssl!(ffi::DSA_sign(hash.as_nid() as c_int,
- message.as_ptr(),
- message.len() as c_int,
- sig.as_mut_ptr(),
- &mut sig_len,
- self.0));
- sig.set_len(sig_len as usize);
- sig.shrink_to_fit();
- Ok(sig)
- }
- }
-
- pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result<bool, ErrorStack> {
- unsafe {
- let result = ffi::DSA_verify(hash.as_nid() as c_int,
- message.as_ptr(),
- message.len() as c_int,
- sig.as_ptr(),
- sig.len() as c_int,
- self.0);
-
- try_ssl_if!(result == -1);
- Ok(result == 1)
- }
- }
-
- pub fn as_ptr(&self) -> *mut ffi::DSA {
- self.0
- }
-
- pub fn p<'a>(&'a self) -> Option<BigNumRef<'a>> {
- unsafe {
- let p = (*self.0).p;
- if p.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr((*self.0).p))
- }
- }
- }
-
- pub fn q<'a>(&'a self) -> Option<BigNumRef<'a>> {
- unsafe {
- let q = (*self.0).q;
- if q.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr((*self.0).q))
- }
- }
- }
-
- pub fn g<'a>(&'a self) -> Option<BigNumRef<'a>> {
- unsafe {
- let g = (*self.0).g;
- if g.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr((*self.0).g))
- }
- }
- }
-
- pub fn has_public_key(&self) -> bool {
- unsafe { !(*self.0).pub_key.is_null() }
- }
-
- pub fn has_private_key(&self) -> bool {
- unsafe { !(*self.0).priv_key.is_null() }
- }
-}
-
-impl fmt::Debug for DSA {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "DSA")
- }
-}
-
-#[cfg(test)]
-mod test {
- use std::io::Write;
- use libc::c_char;
-
- use super::*;
- use crypto::hash::*;
-
- #[test]
- pub fn test_generate() {
- let key = DSA::generate(1024).unwrap();
-
- key.public_key_to_pem().unwrap();
- key.private_key_to_pem().unwrap();
-
- let input: Vec<u8> = (0..25).cycle().take(1024).collect();
-
- let digest = {
- let mut sha = Hasher::new(Type::SHA1).unwrap();
- sha.write_all(&input).unwrap();
- sha.finish().unwrap()
- };
-
- let sig = key.sign(Type::SHA1, &digest).unwrap();
- let verified = key.verify(Type::SHA1, &digest, &sig).unwrap();
- assert!(verified);
- }
-
- #[test]
- pub fn test_sign_verify() {
- let input: Vec<u8> = (0..25).cycle().take(1024).collect();
-
- let private_key = {
- let key = include_bytes!("../../test/dsa.pem");
- DSA::private_key_from_pem(key).unwrap()
- };
-
- let public_key = {
- let key = include_bytes!("../../test/dsa.pem.pub");
- DSA::public_key_from_pem(key).unwrap()
- };
-
- let digest = {
- let mut sha = Hasher::new(Type::SHA1).unwrap();
- sha.write_all(&input).unwrap();
- sha.finish().unwrap()
- };
-
- let sig = private_key.sign(Type::SHA1, &digest).unwrap();
- let verified = public_key.verify(Type::SHA1, &digest, &sig).unwrap();
- assert!(verified);
- }
-
- #[test]
- pub fn test_sign_verify_fail() {
- let input: Vec<u8> = (0..25).cycle().take(128).collect();
- let private_key = {
- let key = include_bytes!("../../test/dsa.pem");
- DSA::private_key_from_pem(key).unwrap()
- };
-
- let public_key = {
- let key = include_bytes!("../../test/dsa.pem.pub");
- DSA::public_key_from_pem(key).unwrap()
- };
-
- let digest = {
- let mut sha = Hasher::new(Type::SHA1).unwrap();
- sha.write_all(&input).unwrap();
- sha.finish().unwrap()
- };
-
- let mut sig = private_key.sign(Type::SHA1, &digest).unwrap();
- // tamper with the sig this should cause a failure
- let len = sig.len();
- sig[len / 2] = 0;
- sig[len - 1] = 0;
- if let Ok(true) = public_key.verify(Type::SHA1, &digest, &sig) {
- panic!("Tampered with signatures should not verify!");
- }
- }
-
- #[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 207a55f5..00000000
--- a/openssl/src/crypto/hash.rs
+++ /dev/null
@@ -1,339 +0,0 @@
-use libc::c_uint;
-use std::io::prelude::*;
-use std::io;
-use std::ptr;
-use std::cmp;
-use ffi;
-
-use HashTypeInternals;
-use error::ErrorStack;
-use nid::Nid;
-
-/// Message digest (hash) type.
-#[derive(Copy, Clone)]
-pub enum Type {
- MD5,
- SHA1,
- SHA224,
- SHA256,
- SHA384,
- SHA512,
- RIPEMD160,
-}
-
-impl HashTypeInternals for Type {
- fn as_nid(&self) -> Nid {
- match *self {
- Type::MD5 => Nid::MD5,
- Type::SHA1 => Nid::SHA1,
- Type::SHA224 => Nid::SHA224,
- Type::SHA256 => Nid::SHA256,
- Type::SHA384 => Nid::SHA384,
- Type::SHA512 => Nid::SHA512,
- Type::RIPEMD160 => Nid::RIPEMD160,
- }
- }
-
- fn evp_md(&self) -> *const ffi::EVP_MD {
- unsafe {
- match *self {
- Type::MD5 => ffi::EVP_md5(),
- Type::SHA1 => ffi::EVP_sha1(),
- Type::SHA224 => ffi::EVP_sha224(),
- Type::SHA256 => ffi::EVP_sha256(),
- Type::SHA384 => ffi::EVP_sha384(),
- Type::SHA512 => ffi::EVP_sha512(),
- Type::RIPEMD160 => ffi::EVP_ripemd160(),
- }
- }
- }
-}
-
-#[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, Type};
-/// 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(Type::MD5, data).unwrap();
-/// assert_eq!(res, spec);
-/// ```
-///
-/// Use the `Write` trait to supply the input in chunks.
-///
-/// ```
-/// use openssl::crypto::hash::{Hasher, Type};
-/// 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(Type::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_: Type,
- state: State,
-}
-
-impl Hasher {
- /// Creates a new `Hasher` with the specified hash type.
- pub fn new(ty: Type) -> Result<Hasher, ErrorStack> {
- ffi::init();
-
- let ctx = unsafe { try_ssl_null!(ffi::EVP_MD_CTX_create()) };
- let md = ty.evp_md();
-
- let mut h = Hasher {
- ctx: ctx,
- md: md,
- 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_ssl!(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *const _)); }
- self.state = Reset;
- Ok(())
- }
-
- /// Feeds data into the hasher.
- pub fn update(&mut self, mut data: &[u8]) -> Result<(), ErrorStack> {
- if self.state == Finalized {
- try!(self.init());
- }
- while !data.is_empty() {
- let len = cmp::min(data.len(), c_uint::max_value() as usize);
- unsafe {
- try_ssl!(ffi::EVP_DigestUpdate(self.ctx, data.as_ptr(), len as c_uint));
- }
- data = &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_ssl!(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 = ffi::EVP_MD_CTX_create();
- 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());
- }
- ffi::EVP_MD_CTX_destroy(self.ctx);
- }
- }
-}
-
-/// Computes the hash of the `data` with the hash `t`.
-pub fn hash(t: Type, 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, Type};
- use std::io::prelude::*;
-
- fn hash_test(hashtype: Type, 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(Type::MD5, test);
- }
- }
-
- #[test]
- fn test_md5_recycle() {
- let mut h = Hasher::new(Type::MD5).unwrap();
- for test in md5_tests.iter() {
- hash_recycle_test(&mut h, test);
- }
- }
-
- #[test]
- fn test_finish_twice() {
- let mut h = Hasher::new(Type::MD5).unwrap();
- h.write_all(&*md5_tests[6].0.from_hex().unwrap()).unwrap();
- h.finish().unwrap();
- let res = h.finish().unwrap();
- let null = hash(Type::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(Type::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(Type::SHA1, test);
- }
- }
-
- #[test]
- fn test_sha256() {
- let tests = [("616263",
- "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")];
-
- for test in tests.iter() {
- hash_test(Type::SHA256, test);
- }
- }
-
- #[test]
- fn test_ripemd160() {
- let tests = [("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")];
-
- for test in tests.iter() {
- hash_test(Type::RIPEMD160, test);
- }
- }
-}
diff --git a/openssl/src/crypto/hmac.rs b/openssl/src/crypto/hmac.rs
deleted file mode 100644
index 1847d6b1..00000000
--- a/openssl/src/crypto/hmac.rs
+++ /dev/null
@@ -1,511 +0,0 @@
-// Copyright 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.
-//
-
-use libc::{c_int, c_uint};
-use std::io;
-use std::io::prelude::*;
-use std::cmp;
-use ffi;
-
-use HashTypeInternals;
-use crypto::hash::Type;
-use error::ErrorStack;
-use c_helpers;
-
-#[derive(PartialEq, Copy, Clone)]
-enum State {
- Reset,
- Updated,
- Finalized,
-}
-
-use self::State::*;
-
-/// Provides HMAC computation.
-///
-/// Requires the `hmac` feature.
-///
-/// # Examples
-///
-/// Calculate a HMAC in one go.
-///
-/// ```
-/// use openssl::crypto::hash::Type;
-/// use openssl::crypto::hmac::hmac;
-/// let key = b"Jefe";
-/// let data = b"what do ya want for nothing?";
-/// let spec = b"\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38";
-/// let res = hmac(Type::MD5, key, data).unwrap();
-/// assert_eq!(res, spec);
-/// ```
-///
-/// Use the `Write` trait to supply the input in chunks.
-///
-/// ```
-/// use openssl::crypto::hash::Type;
-/// use openssl::crypto::hmac::HMAC;
-/// let key = b"Jefe";
-/// let data: &[&[u8]] = &[b"what do ya ", b"want for nothing?"];
-/// let spec = b"\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38";
-/// let mut h = HMAC::new(Type::MD5, &*key).unwrap();
-/// h.update(data[0]).unwrap();
-/// h.update(data[1]).unwrap();
-/// let res = h.finish().unwrap();
-/// assert_eq!(res, spec);
-/// ```
-pub struct HMAC {
- ctx: ffi::HMAC_CTX,
- state: State,
-}
-
-impl HMAC {
- /// Creates a new `HMAC` with the specified hash type using the `key`.
- pub fn new(ty: Type, key: &[u8]) -> Result<HMAC, ErrorStack> {
- ffi::init();
-
- let ctx = unsafe {
- let mut ctx = ::std::mem::uninitialized();
- ffi::HMAC_CTX_init(&mut ctx);
- ctx
- };
- let md = ty.evp_md();
-
- let mut h = HMAC {
- ctx: ctx,
- state: Finalized,
- };
- try!(h.init_once(md, key));
- Ok(h)
- }
-
- fn init_once(&mut self, md: *const ffi::EVP_MD, key: &[u8]) -> Result<(), ErrorStack> {
- unsafe {
- try_ssl!(c_helpers::rust_0_8_HMAC_Init_ex(&mut self.ctx,
- key.as_ptr() as *const _,
- key.len() as c_int,
- md,
- 0 as *mut _));
- }
- self.state = Reset;
- Ok(())
- }
-
- fn init(&mut self) -> Result<(), ErrorStack> {
- match self.state {
- Reset => return Ok(()),
- Updated => {
- try!(self.finish());
- }
- Finalized => (),
- }
- // If the key and/or md is not supplied it's reused from the last time
- // avoiding redundant initializations
- unsafe {
- try_ssl!(c_helpers::rust_0_8_HMAC_Init_ex(&mut self.ctx,
- 0 as *const _,
- 0,
- 0 as *const _,
- 0 as *mut _));
- }
- self.state = Reset;
- Ok(())
- }
-
- pub fn update(&mut self, mut data: &[u8]) -> Result<(), ErrorStack> {
- if self.state == Finalized {
- try!(self.init());
- }
- while !data.is_empty() {
- let len = cmp::min(data.len(), c_uint::max_value() as usize);
- unsafe {
- try_ssl!(c_helpers::rust_0_8_HMAC_Update(&mut self.ctx, data.as_ptr(), len as c_uint));
- }
- data = &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_ssl!(c_helpers::rust_0_8_HMAC_Final(&mut self.ctx, res.as_mut_ptr(), &mut len));
- res.truncate(len as usize);
- self.state = Finalized;
- Ok(res)
- }
- }
-}
-
-impl Write for HMAC {
- #[inline]
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- try!(self.update(buf));
- Ok(buf.len())
- }
-
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
-}
-
-#[cfg(feature = "hmac_clone")]
-impl Clone for HMAC {
- /// Requires the `hmac_clone` feature.
- fn clone(&self) -> HMAC {
- let mut ctx: ffi::HMAC_CTX;
- unsafe {
- ctx = ::std::mem::uninitialized();
- let r = ffi::HMAC_CTX_copy(&mut ctx, &self.ctx);
- assert_eq!(r, 1);
- }
- HMAC {
- ctx: ctx,
- state: self.state,
- }
- }
-}
-
-impl Drop for HMAC {
- fn drop(&mut self) {
- unsafe {
- if self.state != Finalized {
- drop(self.finish());
- }
- ffi::HMAC_CTX_cleanup(&mut self.ctx);
- }
- }
-}
-
-/// Computes the HMAC of the `data` with the hash `t` and `key`.
-pub fn hmac(t: Type, key: &[u8], data: &[u8]) -> Result<Vec<u8>, ErrorStack> {
- let mut h = try!(HMAC::new(t, key));
- try!(h.update(data));
- h.finish()
-}
-
-#[cfg(test)]
-mod tests {
- use std::iter::repeat;
- use serialize::hex::FromHex;
- use crypto::hash::Type;
- use crypto::hash::Type::*;
- use super::{hmac, HMAC};
- use std::io::prelude::*;
-
- fn test_hmac(ty: Type, tests: &[(Vec<u8>, Vec<u8>, Vec<u8>)]) {
- for &(ref key, ref data, ref res) in tests.iter() {
- assert_eq!(hmac(ty, &**key, &**data).unwrap(), *res);
- }
- }
-
- fn test_hmac_recycle(h: &mut HMAC, test: &(Vec<u8>, Vec<u8>, Vec<u8>)) {
- let &(_, ref data, ref res) = test;
- h.write_all(&**data).unwrap();
- assert_eq!(h.finish().unwrap(), *res);
- }
-
- #[test]
- fn test_hmac_md5() {
- // test vectors from RFC 2202
- let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 7] =
- [(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()),
- (repeat(0xaa_u8).take(16).collect(),
- repeat(0xdd_u8).take(50).collect(),
- "56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()),
- ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
- repeat(0xcd_u8).take(50).collect(),
- "697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()),
- (repeat(0x0c_u8).take(16).collect(),
- b"Test With Truncation".to_vec(),
- "56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()),
- (repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
- "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
- (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(MD5, &tests);
- }
-
- #[test]
- fn test_hmac_md5_recycle() {
- let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] =
- [(repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
- "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
- (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())];
-
- let mut h = HMAC::new(MD5, &*tests[0].0).unwrap();
- for i in 0..100usize {
- let test = &tests[i % 2];
- test_hmac_recycle(&mut h, test);
- }
- }
-
- #[test]
- fn test_finish_twice() {
- let test: (Vec<u8>, Vec<u8>, Vec<u8>) =
- (repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
- "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap());
-
- let mut h = HMAC::new(Type::MD5, &*test.0).unwrap();
- h.write_all(&*test.1).unwrap();
- h.finish().unwrap();
- let res = h.finish().unwrap();
- let null = hmac(Type::MD5, &*test.0, &[]).unwrap();
- assert_eq!(res, null);
- }
-
- #[test]
- #[cfg(feature = "hmac_clone")]
- fn test_clone() {
- let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] =
- [(repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
- "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
- (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())];
- let p = tests[0].0.len() / 2;
- let h0 = HMAC::new(Type::MD5, &*tests[0].0).unwrap();
-
- println!("Clone a new hmac");
- let mut h1 = h0.clone();
- h1.write_all(&tests[0].1[..p]).unwrap();
- {
- println!("Clone an updated hmac");
- let mut h2 = h1.clone();
- h2.write_all(&tests[0].1[p..]).unwrap();
- let res = h2.finish().unwrap();
- assert_eq!(res, tests[0].2);
- }
- h1.write_all(&tests[0].1[p..]).unwrap();
- let res = h1.finish().unwrap();
- assert_eq!(res, tests[0].2);
-
- println!("Clone a finished hmac");
- let mut h3 = h1.clone();
- h3.write_all(&*tests[1].1).unwrap();
- let res = h3.finish().unwrap();
- assert_eq!(res, tests[1].2);
- }
-
- #[test]
- fn test_hmac_sha1() {
- // test vectors from RFC 2202
- let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 7] =
- [(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()),
- (repeat(0xaa_u8).take(20).collect(),
- repeat(0xdd_u8).take(50).collect(),
- "125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()),
- ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
- repeat(0xcd_u8).take(50).collect(),
- "4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()),
- (repeat(0x0c_u8).take(20).collect(),
- b"Test With Truncation".to_vec(),
- "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()),
- (repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
- "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()),
- (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(SHA1, &tests);
- }
-
- #[test]
- fn test_hmac_sha1_recycle() {
- let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] =
- [(repeat(0xaa_u8).take(80).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
- "aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()),
- (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())];
-
- let mut h = HMAC::new(SHA1, &*tests[0].0).unwrap();
- for i in 0..100usize {
- let test = &tests[i % 2];
- test_hmac_recycle(&mut h, test);
- }
- }
-
-
-
- fn test_sha2(ty: Type, results: &[Vec<u8>]) {
- // test vectors from RFC 4231
- let tests: [(Vec<u8>, Vec<u8>); 6] =
- [(repeat(0xb_u8).take(20).collect(), b"Hi There".to_vec()),
- (b"Jefe".to_vec(), b"what do ya want for nothing?".to_vec()),
- (repeat(0xaa_u8).take(20).collect(), repeat(0xdd_u8).take(50).collect()),
- ("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
- repeat(0xcd_u8).take(50).collect()),
- (repeat(0xaa_u8).take(131).collect(),
- b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec()),
- (repeat(0xaa_u8).take(131).collect(),
- b"This is a test using a larger than block-size key and a \
- larger than block-size data. The key needs to be hashed \
- before being used by the HMAC algorithm."
- .to_vec())];
-
- for (&(ref key, ref data), res) in tests.iter().zip(results.iter()) {
- assert_eq!(hmac(ty, &**key, &**data).unwrap(), *res);
- }
-
- // recycle test
- let mut h = HMAC::new(ty, &*tests[5].0).unwrap();
- for i in 0..100usize {
- let test = &tests[4 + i % 2];
- let tup = (test.0.clone(), test.1.clone(), results[4 + i % 2].clone());
- test_hmac_recycle(&mut h, &tup);
- }
- }
-
- #[test]
- fn test_hmac_sha224() {
- let results = ["896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22"
- .from_hex()
- .unwrap(),
- "a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44"
- .from_hex()
- .unwrap(),
- "7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea"
- .from_hex()
- .unwrap(),
- "6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a"
- .from_hex()
- .unwrap(),
- "95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e"
- .from_hex()
- .unwrap(),
- "3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1"
- .from_hex()
- .unwrap()];
- test_sha2(SHA224, &results);
- }
-
- #[test]
- fn test_hmac_sha256() {
- let results = ["b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
- .from_hex()
- .unwrap(),
- "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
- .from_hex()
- .unwrap(),
- "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"
- .from_hex()
- .unwrap(),
- "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"
- .from_hex()
- .unwrap(),
- "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"
- .from_hex()
- .unwrap(),
- "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"
- .from_hex()
- .unwrap()];
- test_sha2(SHA256, &results);
- }
-
- #[test]
- fn test_hmac_sha384() {
- let results = ["afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea90\
- 76ede7f4af152e8b2fa9cb6"
- .from_hex()
- .unwrap(),
- "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5\
- e69e2c78b3239ecfab21649"
- .from_hex()
- .unwrap(),
- "88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e55966144b2a5ab39dc\
- 13814b94e3ab6e101a34f27"
- .from_hex()
- .unwrap(),
- "3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e1f573b4e6801dd23c\
- 4a7d679ccf8a386c674cffb"
- .from_hex()
- .unwrap(),
- "4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4\
- 030fe8296248df163f44952"
- .from_hex()
- .unwrap(),
- "6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5a678cc31e\
- 799176d3860e6110c46523e"
- .from_hex()
- .unwrap()];
- test_sha2(SHA384, &results);
- }
-
- #[test]
- fn test_hmac_sha512() {
- let results = ["87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d\
- 6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
- .from_hex()
- .unwrap(),
- "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c\
- 05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
- .from_hex()
- .unwrap(),
- "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e84827\
- 9a722c806b485a47e67c807b946a337bee8942674278859e13292fb"
- .from_hex()
- .unwrap(),
- "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11\
- aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd"
- .from_hex()
- .unwrap(),
- "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e\
- 05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"
- .from_hex()
- .unwrap(),
- "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3\
- c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58"
- .from_hex()
- .unwrap()];
- test_sha2(SHA512, &results);
- }
-}
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 b8b109a2..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.
-//
-
-pub mod hash;
-#[cfg(feature = "hmac")]
-pub mod hmac;
-pub mod pkcs5;
-pub mod pkcs12;
-pub mod pkey;
-pub mod rand;
-pub mod symm;
-pub mod memcmp;
-pub mod rsa;
-pub mod dsa;
-mod util;
diff --git a/openssl/src/crypto/pkcs12.rs b/openssl/src/crypto/pkcs12.rs
deleted file mode 100644
index 89bcbd5c..00000000
--- a/openssl/src/crypto/pkcs12.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-//! PKCS #12 archives.
-
-use ffi;
-use libc::{c_long, c_uchar};
-use std::cmp;
-use std::ptr;
-use std::ffi::CString;
-
-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_ssl_null!(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_ssl!(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 mut chain_out = vec![];
- for i in 0..(*chain).stack.num {
- let x509 = *(*chain).stack.data.offset(i as isize) as *mut _;
- chain_out.push(X509::from_ptr(x509));
- }
- ffi::sk_free(&mut (*chain).stack);
-
- 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(test)]
-mod test {
- use crypto::hash::Type::SHA1;
- 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(SHA1).unwrap().to_hex(),
- "59172d9313e84459bcff27f967e79e6e9217e584");
-
- assert_eq!(parsed.chain.len(), 1);
- assert_eq!(parsed.chain[0].fingerprint(SHA1).unwrap().to_hex(),
- "c0cbdf7cdd03c9773e5468e1f6d2da7d5cbb1875");
- }
-}
diff --git a/openssl/src/crypto/pkcs5.rs b/openssl/src/crypto/pkcs5.rs
deleted file mode 100644
index ef84fbe1..00000000
--- a/openssl/src/crypto/pkcs5.rs
+++ /dev/null
@@ -1,245 +0,0 @@
-use libc::c_int;
-use std::ptr;
-use ffi;
-
-use HashTypeInternals;
-use crypto::hash;
-use crypto::symm;
-use error::ErrorStack;
-
-#[derive(Clone, Eq, PartialEq, Hash, Debug)]
-pub struct KeyIvPair {
- pub key: Vec<u8>,
- pub iv: 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 `pbkdf2_hmac_sha1` or
-/// another more modern key derivation algorithm.
-pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type,
- message_digest_type: hash::Type,
- data: &[u8],
- salt: Option<&[u8]>,
- count: u32)
- -> Result<KeyIvPair, ErrorStack> {
- unsafe {
- 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 typ = typ.as_ptr();
- let message_digest_type = message_digest_type.evp_md();
-
- let len = ffi::EVP_BytesToKey(typ,
- message_digest_type,
- 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 mut key = vec![0; len as usize];
- let mut iv = vec![0; len as usize];
-
- try_ssl!(ffi::EVP_BytesToKey(typ,
- message_digest_type,
- salt_ptr,
- data.as_ptr(),
- data.len() as c_int,
- count as c_int,
- key.as_mut_ptr(),
- iv.as_mut_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(),
- 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.
-#[cfg(feature = "pkcs5_pbkdf2_hmac")]
-pub fn pbkdf2_hmac(pass: &[u8],
- salt: &[u8],
- iter: usize,
- hash: hash::Type,
- keylen: usize)
- -> Result<Vec<u8>, ErrorStack> {
- unsafe {
- let mut out = vec![0; keylen];
- ffi::init();
- try_ssl!(ffi::PKCS5_PBKDF2_HMAC(pass.as_ptr(),
- pass.len() as c_int,
- salt.as_ptr(),
- salt.len() as c_int,
- iter as c_int,
- hash.evp_md(),
- keylen as c_int,
- out.as_mut_ptr()));
- Ok(out)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crypto::hash;
- use crypto::symm;
-
- // 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]
- #[cfg(feature = "pkcs5_pbkdf2_hmac")]
- fn test_pbkdf2_hmac_sha256() {
- assert_eq!(super::pbkdf2_hmac(b"passwd", b"salt", 1, hash::Type::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, hash::Type::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]);
- }
-
- // Test vectors from
- // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c
- #[test]
- #[cfg(feature = "pkcs5_pbkdf2_hmac")]
- fn test_pbkdf2_hmac_sha512() {
- assert_eq!(super::pbkdf2_hmac(b"password", b"NaCL", 1, hash::Type::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, hash::Type::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,
- hash::Type::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]);
- }
- #[test]
- fn test_evp_bytes_to_key_pbkdf1_compatible() {
- 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, 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(symm::Type::AES_256_CBC,
- hash::Type::SHA1,
- &data,
- Some(&salt),
- 1).unwrap(),
- super::KeyIvPair {
- key: expected_key,
- iv: expected_iv,
- });
- }
-}
diff --git a/openssl/src/crypto/pkey.rs b/openssl/src/crypto/pkey.rs
deleted file mode 100644
index a2a6f9c1..00000000
--- a/openssl/src/crypto/pkey.rs
+++ /dev/null
@@ -1,166 +0,0 @@
-use libc::{c_void, c_char};
-use std::ptr;
-use std::mem;
-use ffi;
-
-use bio::{MemBio, MemBioSlice};
-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_ssl_null!(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 _));
- mem::forget(rsa);
- Ok(pkey)
- }
- }
-
- 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_ssl_null!(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_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));
- 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_ssl_null!(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_ssl!(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> {
- unsafe {
- let rsa = try_ssl_null!(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_ssl!(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_ssl!(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 519449e9..00000000
--- a/openssl/src/crypto/rand.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-use libc::c_int;
-use ffi;
-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(())
- }
-}
-
-#[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 feb66a6f..00000000
--- a/openssl/src/crypto/rsa.rs
+++ /dev/null
@@ -1,337 +0,0 @@
-use ffi;
-use std::fmt;
-use std::ptr;
-use std::mem;
-use libc::{c_int, c_void, c_char, c_ulong};
-
-use bn::{BigNum, BigNumRef};
-use bio::{MemBio, MemBioSlice};
-use error::ErrorStack;
-use HashTypeInternals;
-use crypto::hash;
-use crypto::util::{CallbackState, invoke_passwd_cb};
-
-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 = try_ssl_null!(ffi::RSA_new());
- (*rsa).n = n.as_ptr();
- (*rsa).e = e.as_ptr();
- mem::forget(n);
- mem::forget(e);
- Ok(RSA(rsa))
- }
- }
-
- pub fn from_private_components(n: BigNum,
- e: BigNum,
- d: BigNum,
- p: BigNum,
- q: BigNum,
- dp: BigNum,
- dq: BigNum,
- qi: BigNum)
- -> Result<RSA, ErrorStack> {
- unsafe {
- let rsa = try_ssl_null!(ffi::RSA_new());
- (*rsa).n = n.as_ptr();
- (*rsa).e = e.as_ptr();
- (*rsa).d = d.as_ptr();
- (*rsa).p = p.as_ptr();
- (*rsa).q = q.as_ptr();
- (*rsa).dmp1 = dp.as_ptr();
- (*rsa).dmq1 = dq.as_ptr();
- (*rsa).iqmp = qi.as_ptr();
- mem::forget(n);
- mem::forget(e);
- mem::forget(d);
- mem::forget(p);
- mem::forget(q);
- mem::forget(dp);
- mem::forget(dq);
- mem::forget(qi);
- Ok(RSA(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 = try_ssl_null!(ffi::RSA_new());
- let rsa = RSA(rsa);
- let e = try!(BigNum::new_from(ffi::RSA_F4 as c_ulong));
-
- try_ssl!(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_ssl_null!(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_ssl_null!(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_ssl_null!(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_ssl!(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_ssl!(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 sign(&self, hash: hash::Type, message: &[u8]) -> Result<Vec<u8>, ErrorStack> {
- let k_len = self.size().expect("RSA missing an n");
- let mut sig = vec![0; k_len as usize];
- let mut sig_len = k_len;
-
- unsafe {
- try_ssl!(ffi::RSA_sign(hash.as_nid() as c_int,
- message.as_ptr(),
- message.len() as u32,
- sig.as_mut_ptr(),
- &mut sig_len,
- self.0));
- assert!(sig_len == k_len);
- Ok(sig)
- }
- }
-
- pub fn verify(&self, hash: hash::Type, message: &[u8], sig: &[u8]) -> Result<(), ErrorStack> {
- unsafe {
- try_ssl!(ffi::RSA_verify(hash.as_nid() as c_int,
- message.as_ptr(),
- message.len() as u32,
- sig.as_ptr(),
- sig.len() as u32,
- self.0));
- }
- Ok(())
- }
-
- pub fn as_ptr(&self) -> *mut ffi::RSA {
- self.0
- }
-
- pub fn n<'a>(&'a self) -> Option<BigNumRef<'a>> {
- unsafe {
- let n = (*self.0).n;
- if n.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(n))
- }
- }
- }
-
- pub fn d<'a>(&self) -> Option<BigNumRef<'a>> {
- unsafe {
- let d = (*self.0).d;
- if d.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(d))
- }
- }
- }
-
- pub fn e<'a>(&'a self) -> Option<BigNumRef<'a>> {
- unsafe {
- let e = (*self.0).e;
- if e.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(e))
- }
- }
- }
-
- pub fn p<'a>(&'a self) -> Option<BigNumRef<'a>> {
- unsafe {
- let p = (*self.0).p;
- if p.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(p))
- }
- }
- }
-
- pub fn q<'a>(&'a self) -> Option<BigNumRef<'a>> {
- unsafe {
- let q = (*self.0).q;
- if q.is_null() {
- None
- } else {
- Some(BigNumRef::from_ptr(q))
- }
- }
- }
-}
-
-impl fmt::Debug for RSA {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "RSA")
- }
-}
-
-#[cfg(test)]
-mod test {
- use std::io::Write;
- use libc::c_char;
-
- use super::*;
- use crypto::hash::*;
-
- fn signing_input_rs256() -> Vec<u8> {
- vec![101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 122, 73, 49, 78, 105, 74, 57,
- 46, 101, 121, 74, 112, 99, 51, 77, 105, 79, 105, 74, 113, 98, 50, 85, 105, 76, 65, 48,
- 75, 73, 67, 74, 108, 101, 72, 65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84, 107,
- 122, 79, 68, 65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100, 72, 65, 54, 76, 121,
- 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76, 109, 78, 118, 98, 83, 57, 112, 99,
- 49, 57, 121, 98, 50, 57, 48, 73, 106, 112, 48, 99, 110, 86, 108, 102, 81]
- }
-
- fn signature_rs256() -> Vec<u8> {
- vec![112, 46, 33, 137, 67, 232, 143, 209, 30, 181, 216, 45, 191, 120, 69, 243, 65, 6, 174,
- 27, 129, 255, 247, 115, 17, 22, 173, 209, 113, 125, 131, 101, 109, 66, 10, 253, 60,
- 150, 238, 221, 115, 162, 102, 62, 81, 102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237,
- 16, 115, 249, 69, 229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219,
- 61, 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7, 16, 141, 178, 129,
- 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31, 190, 127, 249, 217, 46, 10, 231, 111,
- 36, 242, 91, 51, 187, 230, 244, 74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18,
- 142, 212, 1, 48, 121, 91, 212, 189, 59, 65, 238, 202, 208, 102, 171, 101, 25, 129,
- 253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239, 177, 139, 93, 163,
- 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202, 173, 21, 145, 18, 115, 160, 95, 35,
- 185, 232, 56, 250, 175, 132, 157, 105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195,
- 212, 14, 96, 69, 34, 165, 68, 200, 242, 122, 122, 45, 184, 6, 99, 209, 108, 247, 202,
- 234, 86, 222, 64, 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90, 193, 167, 72, 160,
- 112, 223, 200, 163, 42, 70, 149, 67, 208, 25, 238, 251, 71]
- }
-
- #[test]
- pub fn test_sign() {
- let key = include_bytes!("../../test/rsa.pem");
- let private_key = RSA::private_key_from_pem(key).unwrap();
-
- let mut sha = Hasher::new(Type::SHA256).unwrap();
- sha.write_all(&signing_input_rs256()).unwrap();
- let digest = sha.finish().unwrap();
-
- let result = private_key.sign(Type::SHA256, &digest).unwrap();
-
- assert_eq!(result, signature_rs256());
- }
-
- #[test]
- pub fn test_verify() {
- let key = include_bytes!("../../test/rsa.pem.pub");
- let public_key = RSA::public_key_from_pem(key).unwrap();
-
- let mut sha = Hasher::new(Type::SHA256).unwrap();
- sha.write_all(&signing_input_rs256()).unwrap();
- let digest = sha.finish().unwrap();
-
- assert!(public_key.verify(Type::SHA256, &digest, &signature_rs256()).is_ok());
- }
-
- #[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);
- }
-}
diff --git a/openssl/src/crypto/symm.rs b/openssl/src/crypto/symm.rs
deleted file mode 100644
index 93764e4d..00000000
--- a/openssl/src/crypto/symm.rs
+++ /dev/null
@@ -1,503 +0,0 @@
-use std::cmp;
-use std::ptr;
-use libc::c_int;
-use ffi;
-
-use error::ErrorStack;
-
-#[derive(Copy, Clone)]
-pub enum Mode {
- Encrypt,
- Decrypt,
-}
-
-#[allow(non_camel_case_types)]
-#[derive(Copy, Clone)]
-pub enum Type {
- AES_128_ECB,
- AES_128_CBC,
- /// Requires the `aes_xts` feature
- #[cfg(feature = "aes_xts")]
- AES_128_XTS,
- #[cfg(feature = "aes_ctr")]
- AES_128_CTR,
- // AES_128_GCM,
- AES_128_CFB1,
- AES_128_CFB128,
- AES_128_CFB8,
-
- AES_256_ECB,
- AES_256_CBC,
- /// Requires the `aes_xts` feature
- #[cfg(feature = "aes_xts")]
- AES_256_XTS,
- #[cfg(feature = "aes_ctr")]
- AES_256_CTR,
- // AES_256_GCM,
- AES_256_CFB1,
- AES_256_CFB128,
- AES_256_CFB8,
-
- DES_CBC,
- DES_ECB,
-
- RC4_128,
-}
-
-impl Type {
- pub fn as_ptr(&self) -> *const ffi::EVP_CIPHER {
- unsafe {
- match *self {
- Type::AES_128_ECB => ffi::EVP_aes_128_ecb(),
- Type::AES_128_CBC => ffi::EVP_aes_128_cbc(),
- #[cfg(feature = "aes_xts")]
- Type::AES_128_XTS => ffi::EVP_aes_128_xts(),
- #[cfg(feature = "aes_ctr")]
- Type::AES_128_CTR => ffi::EVP_aes_128_ctr(),
- // AES_128_GCM => (EVP_aes_128_gcm(), 16, 16),
- Type::AES_128_CFB1 => ffi::EVP_aes_128_cfb1(),
- Type::AES_128_CFB128 => ffi::EVP_aes_128_cfb128(),
- Type::AES_128_CFB8 => ffi::EVP_aes_128_cfb8(),
-
- Type::AES_256_ECB => ffi::EVP_aes_256_ecb(),
- Type::AES_256_CBC => ffi::EVP_aes_256_cbc(),
- #[cfg(feature = "aes_xts")]
- Type::AES_256_XTS => ffi::EVP_aes_256_xts(),
- #[cfg(feature = "aes_ctr")]
- Type::AES_256_CTR => ffi::EVP_aes_256_ctr(),
- // AES_256_GCM => (EVP_aes_256_gcm(), 32, 16),
- Type::AES_256_CFB1 => ffi::EVP_aes_256_cfb1(),
- Type::AES_256_CFB128 => ffi::EVP_aes_256_cfb128(),
- Type::AES_256_CFB8 => ffi::EVP_aes_256_cfb8(),
-
- Type::DES_CBC => ffi::EVP_des_cbc(),
- Type::DES_ECB => ffi::EVP_des_ecb(),
-
- Type::RC4_128 => ffi::EVP_rc4(),
- }
- }
- }
-
- /// Returns the length of keys used with this cipher.
- pub fn key_len(&self) -> usize {
- unsafe {
- ffi::EVP_CIPHER_key_length(self.as_ptr()) 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 = ffi::EVP_CIPHER_iv_length(self.as_ptr()) 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 {
- ffi::EVP_CIPHER_block_size(self.as_ptr()) 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 `Type::iv_len`).
- pub fn new(t: Type, mode: Mode, key: &[u8], iv: Option<&[u8]>) -> Result<Crypter, ErrorStack> {
- ffi::init();
-
- unsafe {
- let ctx = try_ssl_null!(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_ssl!(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));
-
- 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_ssl!(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 `Type::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_ssl!(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_ssl!(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: Type,
- 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: Type,
- key: &[u8],
- iv: Option<&[u8]>,
- data: &[u8])
- -> Result<Vec<u8>, ErrorStack> {
- cipher(t, Mode::Decrypt, key, iv, data)
-}
-
-fn cipher(t: Type,
- 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(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::Type::AES_256_ECB,
- super::Mode::Encrypt,
- &k0,
- None).unwrap();
- c.pad(false);
- let mut r0 = vec![0; c0.len() + super::Type::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::Type::AES_256_ECB,
- super::Mode::Decrypt,
- &k0,
- None).unwrap();
- c.pad(false);
- let mut p1 = vec![0; r0.len() + super::Type::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::Type::AES_256_CBC,
- super::Mode::Decrypt,
- &data,
- Some(&iv)).unwrap();
- cr.pad(false);
- let mut unciphered_data = vec![0; data.len() + super::Type::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::Type, 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::Type::RC4_128, pt, ct, key, iv);
- }
-
- #[test]
- #[cfg(feature = "aes_xts")]
- 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::Type::AES_256_XTS, pt, ct, key, iv);
- }
-
- #[test]
- #[cfg(feature = "aes_ctr")]
- fn test_aes128_ctr() {
-
- let pt = "6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411\
- E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710";
- let ct = "874D6191B620E3261BEF6864990DB6CE9806F66B7970FDFF8617187BB9FFFDFF5AE4DF3EDBD5D35E\
- 5B4F09020DB03EAB1E031DDA2FBE03D1792170A0F3009CEE";
- let key = "2B7E151628AED2A6ABF7158809CF4F3C";
- let iv = "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
-
- cipher_test(super::Type::AES_128_CTR, pt, ct, key, iv);
- }
-
- // #[test]
- // fn test_aes128_gcm() {
- // Test case 3 in GCM spec
- // let pt = ~"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255";
- // let ct = ~"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f59854d5c2af327cd64a62cf35abd2ba6fab4";
- // let key = ~"feffe9928665731c6d6a8f9467308308";
- // let iv = ~"cafebabefacedbaddecaf888";
- //
- // cipher_test(super::AES_128_GCM, 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::Type::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::Type::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::Type::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::Type::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::Type::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::Type::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::Type::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::Type::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 c11285f8..00000000
--- a/openssl/src/crypto/util.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-use libc::{c_int, c_char, c_void};
-
-use std::any::Any;
-use std::panic;
-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 extern "C" 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 result = panic::catch_unwind(|| {
- // build a `i8` slice to pass to the user callback
- let pass_slice = unsafe { slice::from_raw_parts_mut(buf, size as usize) };
- let callback = unsafe { &mut *(cb_state as *mut CallbackState<F>) };
-
- callback.cb.take().unwrap()(pass_slice)
- });
-
- if let Ok(len) = result {
- return len as c_int;
- } else {
- return 0;
- }
-}