Merge branch 'release-v0.7.3' into release
This commit is contained in:
commit
6195bd4fd8
25
.travis.yml
25
.travis.yml
|
|
@ -1,18 +1,29 @@
|
||||||
language: rust
|
language: rust
|
||||||
sudo: false
|
sudo: false
|
||||||
|
addons:
|
||||||
|
apt:
|
||||||
|
packages:
|
||||||
|
- gcc-arm-linux-gnueabihf
|
||||||
rust:
|
rust:
|
||||||
- nightly
|
- nightly
|
||||||
- beta
|
- beta
|
||||||
- stable
|
- 1.4.0
|
||||||
os:
|
os:
|
||||||
- osx
|
- osx
|
||||||
- linux
|
- linux
|
||||||
env:
|
env:
|
||||||
global:
|
matrix:
|
||||||
- FEATURES="tlsv1_2 tlsv1_1 dtlsv1 dtlsv1_2 sslv2 sslv3 aes_xts aes_ctr npn alpn rfc5114 ecdh_auto pkcs5_pbkdf2_hmac"
|
- TEST_FEATURES=false
|
||||||
|
- TEST_FEATURES=true
|
||||||
|
matrix:
|
||||||
|
# include:
|
||||||
|
# - os: linux
|
||||||
|
# env: TARGET=arm-unknown-linux-gnueabihf TEST_FEATURES=true
|
||||||
|
# rust: 1.4.0
|
||||||
|
exclude:
|
||||||
|
- os: osx
|
||||||
|
env: TEST_FEATURES=true
|
||||||
before_install:
|
before_install:
|
||||||
- (test $TRAVIS_OS_NAME == "osx" || ./openssl/test/build.sh)
|
- ./openssl/test/build.sh
|
||||||
script:
|
script:
|
||||||
- (test $TRAVIS_OS_NAME != "osx" || (cd openssl && cargo test))
|
- ./openssl/test/run.sh
|
||||||
- (test $TRAVIS_OS_NAME == "osx" || (cd openssl && OPENSSL_LIB_DIR=$HOME/openssl/lib OPENSSL_INCLUDE_DIR=$HOME/openssl/include LD_LIBRARY_PATH=$HOME/openssl/lib:$LD_LIBRARY_PATH PATH=$HOME/openssl/bin:$PATH cargo test))
|
|
||||||
- (test $TRAVIS_OS_NAME == "osx" || (cd openssl && OPENSSL_LIB_DIR=$HOME/openssl/lib OPENSSL_INCLUDE_DIR=$HOME/openssl/include LD_LIBRARY_PATH=$HOME/openssl/lib:$LD_LIBRARY_PATH PATH=$HOME/openssl/bin:$PATH cargo test --features "$FEATURES"))
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
[](https://travis-ci.org/sfackler/rust-openssl)
|
[](https://travis-ci.org/sfackler/rust-openssl)
|
||||||
|
|
||||||
[Documentation](https://sfackler.github.io/rust-openssl/doc/v0.7.2/openssl).
|
[Documentation](https://sfackler.github.io/rust-openssl/doc/v0.7.3/openssl).
|
||||||
|
|
||||||
## Building
|
## Building
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
[package]
|
[package]
|
||||||
name = "openssl-sys-extras"
|
name = "openssl-sys-extras"
|
||||||
version = "0.7.2"
|
version = "0.7.3"
|
||||||
authors = ["Steven Fackler <sfackler@gmail.com>"]
|
authors = ["Steven Fackler <sfackler@gmail.com>"]
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
description = "Extra FFI bindings to OpenSSL that require a C shim"
|
description = "Extra FFI bindings to OpenSSL that require a C shim"
|
||||||
repository = "https://github.com/sfackler/rust-openssl"
|
repository = "https://github.com/sfackler/rust-openssl"
|
||||||
documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.2/openssl_sys_extras"
|
documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.3/openssl_sys_extras"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
|
|
@ -13,7 +13,7 @@ ecdh_auto = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
openssl-sys = { version = "0.7.1", path = "../openssl-sys" }
|
openssl-sys = { version = "0.7.3", path = "../openssl-sys" }
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
gcc = "0.3"
|
gcc = "0.3"
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
#![allow(non_upper_case_globals, non_snake_case)]
|
#![allow(non_upper_case_globals, non_snake_case)]
|
||||||
#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.2")]
|
#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.3")]
|
||||||
|
|
||||||
extern crate openssl_sys;
|
extern crate openssl_sys;
|
||||||
extern crate libc;
|
extern crate libc;
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,12 @@
|
||||||
[package]
|
[package]
|
||||||
name = "openssl-sys"
|
name = "openssl-sys"
|
||||||
version = "0.7.2"
|
version = "0.7.3"
|
||||||
authors = ["Alex Crichton <alex@alexcrichton.com>",
|
authors = ["Alex Crichton <alex@alexcrichton.com>",
|
||||||
"Steven Fackler <sfackler@gmail.com>"]
|
"Steven Fackler <sfackler@gmail.com>"]
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
description = "FFI bindings to OpenSSL"
|
description = "FFI bindings to OpenSSL"
|
||||||
repository = "https://github.com/sfackler/rust-openssl"
|
repository = "https://github.com/sfackler/rust-openssl"
|
||||||
documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.2/openssl_sys"
|
documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.3/openssl_sys"
|
||||||
links = "openssl"
|
links = "openssl"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)]
|
#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)]
|
||||||
#![allow(dead_code)]
|
#![allow(dead_code)]
|
||||||
#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.2")]
|
#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.3")]
|
||||||
|
|
||||||
extern crate libc;
|
extern crate libc;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,11 @@
|
||||||
[package]
|
[package]
|
||||||
name = "openssl"
|
name = "openssl"
|
||||||
version = "0.7.2"
|
version = "0.7.3"
|
||||||
authors = ["Steven Fackler <sfackler@gmail.com>"]
|
authors = ["Steven Fackler <sfackler@gmail.com>"]
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
description = "OpenSSL bindings"
|
description = "OpenSSL bindings"
|
||||||
repository = "https://github.com/sfackler/rust-openssl"
|
repository = "https://github.com/sfackler/rust-openssl"
|
||||||
documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.2/openssl"
|
documentation = "https://sfackler.github.io/rust-openssl/doc/v0.7.3/openssl"
|
||||||
readme = "../README.md"
|
readme = "../README.md"
|
||||||
keywords = ["crypto", "tls", "ssl", "dtls"]
|
keywords = ["crypto", "tls", "ssl", "dtls"]
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
@ -29,8 +29,8 @@ pkcs5_pbkdf2_hmac = ["openssl-sys/pkcs5_pbkdf2_hmac"]
|
||||||
bitflags = ">= 0.2, < 0.4"
|
bitflags = ">= 0.2, < 0.4"
|
||||||
lazy_static = "0.1"
|
lazy_static = "0.1"
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
openssl-sys = { version = "0.7.1", path = "../openssl-sys" }
|
openssl-sys = { version = "0.7.3", path = "../openssl-sys" }
|
||||||
openssl-sys-extras = { version = "0.7.1", path = "../openssl-sys-extras" }
|
openssl-sys-extras = { version = "0.7.3", path = "../openssl-sys-extras" }
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
gcc = "0.3"
|
gcc = "0.3"
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
use libc::{c_long};
|
use libc::c_long;
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
|
|
||||||
use ffi;
|
use ffi;
|
||||||
use ssl::error::{SslError};
|
use ssl::error::SslError;
|
||||||
|
|
||||||
|
|
||||||
pub struct Asn1Time {
|
pub struct Asn1Time {
|
||||||
handle: *mut ffi::ASN1_TIME,
|
handle: *mut ffi::ASN1_TIME,
|
||||||
owned: bool
|
owned: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Asn1Time {
|
impl Asn1Time {
|
||||||
|
|
@ -15,7 +15,7 @@ impl Asn1Time {
|
||||||
pub fn new(handle: *mut ffi::ASN1_TIME) -> Asn1Time {
|
pub fn new(handle: *mut ffi::ASN1_TIME) -> Asn1Time {
|
||||||
Asn1Time {
|
Asn1Time {
|
||||||
handle: handle,
|
handle: handle,
|
||||||
owned: true
|
owned: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -23,8 +23,7 @@ impl Asn1Time {
|
||||||
ffi::init();
|
ffi::init();
|
||||||
|
|
||||||
let handle = unsafe {
|
let handle = unsafe {
|
||||||
try_ssl_null!(ffi::X509_gmtime_adj(ptr::null_mut(),
|
try_ssl_null!(ffi::X509_gmtime_adj(ptr::null_mut(), period as c_long))
|
||||||
period as c_long))
|
|
||||||
};
|
};
|
||||||
Ok(Asn1Time::new(handle))
|
Ok(Asn1Time::new(handle))
|
||||||
}
|
}
|
||||||
|
|
@ -36,7 +35,7 @@ impl Asn1Time {
|
||||||
|
|
||||||
/// Returns raw handle
|
/// Returns raw handle
|
||||||
pub unsafe fn get_handle(&self) -> *mut ffi::ASN1_TIME {
|
pub unsafe fn get_handle(&self) -> *mut ffi::ASN1_TIME {
|
||||||
return self.handle
|
return self.handle;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,11 +6,11 @@ use std::cmp;
|
||||||
|
|
||||||
use ffi;
|
use ffi;
|
||||||
use ffi_extras;
|
use ffi_extras;
|
||||||
use ssl::error::{SslError};
|
use ssl::error::SslError;
|
||||||
|
|
||||||
pub struct MemBio {
|
pub struct MemBio {
|
||||||
bio: *mut ffi::BIO,
|
bio: *mut ffi::BIO,
|
||||||
owned: bool
|
owned: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for MemBio {
|
impl Drop for MemBio {
|
||||||
|
|
@ -33,7 +33,7 @@ impl MemBio {
|
||||||
|
|
||||||
Ok(MemBio {
|
Ok(MemBio {
|
||||||
bio: bio,
|
bio: bio,
|
||||||
owned: true
|
owned: true,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -41,7 +41,7 @@ impl MemBio {
|
||||||
pub fn borrowed(bio: *mut ffi::BIO) -> MemBio {
|
pub fn borrowed(bio: *mut ffi::BIO) -> MemBio {
|
||||||
MemBio {
|
MemBio {
|
||||||
bio: bio,
|
bio: bio,
|
||||||
owned: false
|
owned: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -60,17 +60,21 @@ impl MemBio {
|
||||||
|
|
||||||
/// Sets the BIO's EOF state.
|
/// Sets the BIO's EOF state.
|
||||||
pub fn set_eof(&self, eof: bool) {
|
pub fn set_eof(&self, eof: bool) {
|
||||||
let v = if eof { 0 } else { -1 };
|
let v = if eof {
|
||||||
unsafe { ffi_extras::BIO_set_mem_eof_return(self.bio, v); }
|
0
|
||||||
|
} else {
|
||||||
|
-1
|
||||||
|
};
|
||||||
|
unsafe {
|
||||||
|
ffi_extras::BIO_set_mem_eof_return(self.bio, v);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Read for MemBio {
|
impl Read for MemBio {
|
||||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int;
|
let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int;
|
||||||
let ret = unsafe {
|
let ret = unsafe { ffi::BIO_read(self.bio, buf.as_ptr() as *mut c_void, len) };
|
||||||
ffi::BIO_read(self.bio, buf.as_ptr() as *mut c_void, len)
|
|
||||||
};
|
|
||||||
|
|
||||||
if ret <= 0 {
|
if ret <= 0 {
|
||||||
let is_eof = unsafe { ffi_extras::BIO_eof(self.bio) };
|
let is_eof = unsafe { ffi_extras::BIO_eof(self.bio) };
|
||||||
|
|
@ -88,9 +92,7 @@ impl Read for MemBio {
|
||||||
impl Write for MemBio {
|
impl Write for MemBio {
|
||||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int;
|
let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int;
|
||||||
let ret = unsafe {
|
let ret = unsafe { ffi::BIO_write(self.bio, buf.as_ptr() as *const c_void, len) };
|
||||||
ffi::BIO_write(self.bio, buf.as_ptr() as *const c_void, len)
|
|
||||||
};
|
|
||||||
|
|
||||||
if ret < 0 {
|
if ret < 0 {
|
||||||
Err(io::Error::new(io::ErrorKind::Other, SslError::get()))
|
Err(io::Error::new(io::ErrorKind::Other, SslError::get()))
|
||||||
|
|
|
||||||
|
|
@ -111,55 +111,73 @@ impl BigNum {
|
||||||
|
|
||||||
pub fn checked_sqr(&self) -> Result<BigNum, SslError> {
|
pub fn checked_sqr(&self) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_sqr(r.raw(), self.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_sqr(r.raw(), self.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_nnmod(&self, n: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_nnmod(&self, n: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_nnmod(r.raw(), self.raw(), n.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_nnmod(r.raw(), self.raw(), n.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_mod_add(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_mod_add(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_mod_add(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_mod_add(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_mod_sub(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_mod_sub(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_mod_sub(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_mod_sub(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_mod_mul(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_mod_mul(&self, a: &BigNum, n: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_mod_mul(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_mod_mul(r.raw(), self.raw(), a.raw(), n.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_mod_sqr(&self, n: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_mod_sqr(&self, n: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_mod_sqr(r.raw(), self.raw(), n.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_mod_sqr(r.raw(), self.raw(), n.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_exp(&self, p: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_exp(&self, p: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_exp(r.raw(), self.raw(), p.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_exp(r.raw(), self.raw(), p.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_mod_exp(&self, p: &BigNum, n: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_mod_exp(&self, p: &BigNum, n: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_mod_exp(r.raw(), self.raw(), p.raw(), n.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_mod_exp(r.raw(), self.raw(), p.raw(), n.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_mod_inv(&self, n: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_mod_inv(&self, n: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { !ffi::BN_mod_inverse(r.raw(), self.raw(), n.raw(), ctx).is_null() })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
!ffi::BN_mod_inverse(r.raw(), self.raw(), n.raw(), ctx).is_null()
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -217,17 +235,28 @@ impl BigNum {
|
||||||
|
|
||||||
pub fn checked_gcd(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_gcd(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_gcd(r.raw(), self.raw(), a.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_gcd(r.raw(), self.raw(), a.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_generate_prime(bits: i32, safe: bool, add: Option<&BigNum>, rem: Option<&BigNum>) -> Result<BigNum, SslError> {
|
pub fn checked_generate_prime(bits: i32,
|
||||||
|
safe: bool,
|
||||||
|
add: Option<&BigNum>,
|
||||||
|
rem: Option<&BigNum>)
|
||||||
|
-> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, {
|
with_bn_in_ctx!(r, ctx, {
|
||||||
let add_arg = add.map(|a| a.raw()).unwrap_or(ptr::null_mut());
|
let add_arg = add.map(|a| a.raw()).unwrap_or(ptr::null_mut());
|
||||||
let rem_arg = rem.map(|r| r.raw()).unwrap_or(ptr::null_mut());
|
let rem_arg = rem.map(|r| r.raw()).unwrap_or(ptr::null_mut());
|
||||||
|
|
||||||
ffi::BN_generate_prime_ex(r.raw(), bits as c_int, safe as c_int, add_arg, rem_arg, ptr::null()) == 1
|
ffi::BN_generate_prime_ex(r.raw(),
|
||||||
|
bits as c_int,
|
||||||
|
safe as c_int,
|
||||||
|
add_arg,
|
||||||
|
rem_arg,
|
||||||
|
ptr::null()) == 1
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -243,32 +272,47 @@ impl BigNum {
|
||||||
pub fn is_prime_fast(&self, checks: i32, do_trial_division: bool) -> Result<bool, SslError> {
|
pub fn is_prime_fast(&self, checks: i32, do_trial_division: bool) -> Result<bool, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_ctx!(ctx, {
|
with_ctx!(ctx, {
|
||||||
Ok(ffi::BN_is_prime_fasttest_ex(self.raw(), checks as c_int, ctx, do_trial_division as c_int, ptr::null()) == 1)
|
Ok(ffi::BN_is_prime_fasttest_ex(self.raw(),
|
||||||
|
checks as c_int,
|
||||||
|
ctx,
|
||||||
|
do_trial_division as c_int,
|
||||||
|
ptr::null()) == 1)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_new_random(bits: i32, prop: RNGProperty, odd: bool) -> Result<BigNum, SslError> {
|
pub fn checked_new_random(bits: i32, prop: RNGProperty, odd: bool) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_rand(r.raw(), bits as c_int, prop as c_int, odd as c_int) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_rand(r.raw(), bits as c_int, prop as c_int, odd as c_int) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_new_pseudo_random(bits: i32, prop: RNGProperty, odd: bool) -> Result<BigNum, SslError> {
|
pub fn checked_new_pseudo_random(bits: i32,
|
||||||
|
prop: RNGProperty,
|
||||||
|
odd: bool)
|
||||||
|
-> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_pseudo_rand(r.raw(), bits as c_int, prop as c_int, odd as c_int) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_pseudo_rand(r.raw(), bits as c_int, prop as c_int, odd as c_int) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_rand_in_range(&self) -> Result<BigNum, SslError> {
|
pub fn checked_rand_in_range(&self) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_rand_range(r.raw(), self.raw()) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_rand_range(r.raw(), self.raw()) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_pseudo_rand_in_range(&self) -> Result<BigNum, SslError> {
|
pub fn checked_pseudo_rand_in_range(&self) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_pseudo_rand_range(r.raw(), self.raw()) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_pseudo_rand_range(r.raw(), self.raw()) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -293,9 +337,7 @@ impl BigNum {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_bit_set(&self, n: i32) -> bool {
|
pub fn is_bit_set(&self, n: i32) -> bool {
|
||||||
unsafe {
|
unsafe { ffi::BN_is_bit_set(self.raw(), n as c_int) == 1 }
|
||||||
ffi::BN_is_bit_set(self.raw(), n as c_int) == 1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mask_bits(&mut self, n: i32) -> Result<(), SslError> {
|
pub fn mask_bits(&mut self, n: i32) -> Result<(), SslError> {
|
||||||
|
|
@ -310,62 +352,78 @@ impl BigNum {
|
||||||
|
|
||||||
pub fn checked_shl1(&self) -> Result<BigNum, SslError> {
|
pub fn checked_shl1(&self) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn!(r, { ffi::BN_lshift1(r.raw(), self.raw()) == 1 })
|
with_bn!(r, {
|
||||||
|
ffi::BN_lshift1(r.raw(), self.raw()) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_shr1(&self) -> Result<BigNum, SslError> {
|
pub fn checked_shr1(&self) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn!(r, { ffi::BN_rshift1(r.raw(), self.raw()) == 1 })
|
with_bn!(r, {
|
||||||
|
ffi::BN_rshift1(r.raw(), self.raw()) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_add(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_add(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn!(r, { ffi::BN_add(r.raw(), self.raw(), a.raw()) == 1 })
|
with_bn!(r, {
|
||||||
|
ffi::BN_add(r.raw(), self.raw(), a.raw()) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_sub(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_sub(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn!(r, { ffi::BN_sub(r.raw(), self.raw(), a.raw()) == 1 })
|
with_bn!(r, {
|
||||||
|
ffi::BN_sub(r.raw(), self.raw(), a.raw()) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_mul(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_mul(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_mul(r.raw(), self.raw(), a.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_mul(r.raw(), self.raw(), a.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_div(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_div(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_div(r.raw(), ptr::null_mut(), self.raw(), a.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_div(r.raw(), ptr::null_mut(), self.raw(), a.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_mod(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
pub fn checked_mod(&self, a: &BigNum) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn_in_ctx!(r, ctx, { ffi::BN_div(ptr::null_mut(), r.raw(), self.raw(), a.raw(), ctx) == 1 })
|
with_bn_in_ctx!(r, ctx, {
|
||||||
|
ffi::BN_div(ptr::null_mut(), r.raw(), self.raw(), a.raw(), ctx) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_shl(&self, a: &i32) -> Result<BigNum, SslError> {
|
pub fn checked_shl(&self, a: &i32) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn!(r, { ffi::BN_lshift(r.raw(), self.raw(), *a as c_int) == 1 })
|
with_bn!(r, {
|
||||||
|
ffi::BN_lshift(r.raw(), self.raw(), *a as c_int) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn checked_shr(&self, a: &i32) -> Result<BigNum, SslError> {
|
pub fn checked_shr(&self, a: &i32) -> Result<BigNum, SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
with_bn!(r, { ffi::BN_rshift(r.raw(), self.raw(), *a as c_int) == 1 })
|
with_bn!(r, {
|
||||||
|
ffi::BN_rshift(r.raw(), self.raw(), *a as c_int) == 1
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn negate(&mut self) {
|
pub fn negate(&mut self) {
|
||||||
unsafe {
|
unsafe { ffi::BN_set_negative(self.raw(), !self.is_negative() as c_int) }
|
||||||
ffi::BN_set_negative(self.raw(), !self.is_negative() as c_int)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn abs_cmp(&self, oth: BigNum) -> Ordering {
|
pub fn abs_cmp(&self, oth: BigNum) -> Ordering {
|
||||||
|
|
@ -382,15 +440,11 @@ impl BigNum {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_negative(&self) -> bool {
|
pub fn is_negative(&self) -> bool {
|
||||||
unsafe {
|
unsafe { (*self.raw()).neg == 1 }
|
||||||
(*self.raw()).neg == 1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn num_bits(&self) -> i32 {
|
pub fn num_bits(&self) -> i32 {
|
||||||
unsafe {
|
unsafe { ffi::BN_num_bits(self.raw()) as i32 }
|
||||||
ffi::BN_num_bits(self.raw()) as i32
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn num_bytes(&self) -> i32 {
|
pub fn num_bytes(&self) -> i32 {
|
||||||
|
|
@ -421,7 +475,8 @@ impl BigNum {
|
||||||
unsafe {
|
unsafe {
|
||||||
let buf = ffi::BN_bn2dec(self.raw());
|
let buf = ffi::BN_bn2dec(self.raw());
|
||||||
assert!(!buf.is_null());
|
assert!(!buf.is_null());
|
||||||
let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()).unwrap();
|
let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec())
|
||||||
|
.unwrap();
|
||||||
ffi::CRYPTO_free(buf as *mut c_void);
|
ffi::CRYPTO_free(buf as *mut c_void);
|
||||||
str
|
str
|
||||||
}
|
}
|
||||||
|
|
@ -431,7 +486,8 @@ impl BigNum {
|
||||||
unsafe {
|
unsafe {
|
||||||
let buf = ffi::BN_bn2hex(self.raw());
|
let buf = ffi::BN_bn2hex(self.raw());
|
||||||
assert!(!buf.is_null());
|
assert!(!buf.is_null());
|
||||||
let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec()).unwrap();
|
let str = String::from_utf8(CStr::from_ptr(buf as *const _).to_bytes().to_vec())
|
||||||
|
.unwrap();
|
||||||
ffi::CRYPTO_free(buf as *mut c_void);
|
ffi::CRYPTO_free(buf as *mut c_void);
|
||||||
str
|
str
|
||||||
}
|
}
|
||||||
|
|
@ -444,12 +500,10 @@ impl fmt::Debug for BigNum {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Eq for BigNum { }
|
impl Eq for BigNum {}
|
||||||
impl PartialEq for BigNum {
|
impl PartialEq for BigNum {
|
||||||
fn eq(&self, oth: &BigNum) -> bool {
|
fn eq(&self, oth: &BigNum) -> bool {
|
||||||
unsafe {
|
unsafe { ffi::BN_cmp(self.raw(), oth.raw()) == 0 }
|
||||||
ffi::BN_cmp(self.raw(), oth.raw()) == 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -463,14 +517,13 @@ impl PartialOrd for BigNum {
|
||||||
fn partial_cmp(&self, oth: &BigNum) -> Option<Ordering> {
|
fn partial_cmp(&self, oth: &BigNum) -> Option<Ordering> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let v = ffi::BN_cmp(self.raw(), oth.raw());
|
let v = ffi::BN_cmp(self.raw(), oth.raw());
|
||||||
let ret =
|
let ret = if v == 0 {
|
||||||
if v == 0 {
|
Ordering::Equal
|
||||||
Ordering::Equal
|
} else if v < 0 {
|
||||||
} else if v < 0 {
|
Ordering::Less
|
||||||
Ordering::Less
|
} else {
|
||||||
} else {
|
Ordering::Greater
|
||||||
Ordering::Greater
|
};
|
||||||
};
|
|
||||||
Some(ret)
|
Some(ret)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -489,7 +542,7 @@ impl Drop for BigNum {
|
||||||
pub mod unchecked {
|
pub mod unchecked {
|
||||||
use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub};
|
use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub};
|
||||||
use ffi;
|
use ffi;
|
||||||
use super::{BigNum};
|
use super::BigNum;
|
||||||
|
|
||||||
impl<'a> Add<&'a BigNum> for &'a BigNum {
|
impl<'a> Add<&'a BigNum> for &'a BigNum {
|
||||||
type Output = BigNum;
|
type Output = BigNum;
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ pub enum Type {
|
||||||
SHA256,
|
SHA256,
|
||||||
SHA384,
|
SHA384,
|
||||||
SHA512,
|
SHA512,
|
||||||
RIPEMD160
|
RIPEMD160,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Type {
|
impl Type {
|
||||||
|
|
@ -112,7 +112,12 @@ impl Hasher {
|
||||||
};
|
};
|
||||||
let md = ty.evp_md();
|
let md = ty.evp_md();
|
||||||
|
|
||||||
let mut h = Hasher { ctx: ctx, md: md, type_: ty, state: Finalized };
|
let mut h = Hasher {
|
||||||
|
ctx: ctx,
|
||||||
|
md: md,
|
||||||
|
type_: ty,
|
||||||
|
state: Finalized,
|
||||||
|
};
|
||||||
h.init();
|
h.init();
|
||||||
h
|
h
|
||||||
}
|
}
|
||||||
|
|
@ -121,7 +126,9 @@ impl Hasher {
|
||||||
fn init(&mut self) {
|
fn init(&mut self) {
|
||||||
match self.state {
|
match self.state {
|
||||||
Reset => return,
|
Reset => return,
|
||||||
Updated => { self.finalize(); },
|
Updated => {
|
||||||
|
self.finalize();
|
||||||
|
}
|
||||||
Finalized => (),
|
Finalized => (),
|
||||||
}
|
}
|
||||||
unsafe {
|
unsafe {
|
||||||
|
|
@ -137,8 +144,7 @@ impl Hasher {
|
||||||
self.init();
|
self.init();
|
||||||
}
|
}
|
||||||
unsafe {
|
unsafe {
|
||||||
let r = ffi::EVP_DigestUpdate(self.ctx, data.as_ptr(),
|
let r = ffi::EVP_DigestUpdate(self.ctx, data.as_ptr(), data.len() as c_uint);
|
||||||
data.len() as c_uint);
|
|
||||||
assert_eq!(r, 1);
|
assert_eq!(r, 1);
|
||||||
}
|
}
|
||||||
self.state = Updated;
|
self.state = Updated;
|
||||||
|
|
@ -190,7 +196,12 @@ impl Clone for Hasher {
|
||||||
assert_eq!(r, 1);
|
assert_eq!(r, 1);
|
||||||
ctx
|
ctx
|
||||||
};
|
};
|
||||||
Hasher { ctx: ctx, md: self.md, type_: self.type_, state: self.state }
|
Hasher {
|
||||||
|
ctx: ctx,
|
||||||
|
md: self.md,
|
||||||
|
type_: self.type_,
|
||||||
|
state: self.state,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -233,21 +244,32 @@ mod tests {
|
||||||
|
|
||||||
// Test vectors from http://www.nsrl.nist.gov/testdata/
|
// Test vectors from http://www.nsrl.nist.gov/testdata/
|
||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
const md5_tests: [(&'static str, &'static str); 13] = [
|
const md5_tests: [(&'static str, &'static str); 13] = [("",
|
||||||
("", "d41d8cd98f00b204e9800998ecf8427e"),
|
"d41d8cd98f00b204e9800998ecf8427e"),
|
||||||
("7F", "83acb6e67e50e31db6ed341dd2de1595"),
|
("7F",
|
||||||
("EC9C", "0b07f0d4ca797d8ac58874f887cb0b68"),
|
"83acb6e67e50e31db6ed341dd2de1595"),
|
||||||
("FEE57A", "e0d583171eb06d56198fc0ef22173907"),
|
("EC9C",
|
||||||
("42F497E0", "7c430f178aefdf1487fee7144e9641e2"),
|
"0b07f0d4ca797d8ac58874f887cb0b68"),
|
||||||
("C53B777F1C", "75ef141d64cb37ec423da2d9d440c925"),
|
("FEE57A",
|
||||||
("89D5B576327B", "ebbaf15eb0ed784c6faa9dc32831bf33"),
|
"e0d583171eb06d56198fc0ef22173907"),
|
||||||
("5D4CCE781EB190", "ce175c4b08172019f05e6b5279889f2c"),
|
("42F497E0",
|
||||||
("81901FE94932D7B9", "cd4d2f62b8cdb3a0cf968a735a239281"),
|
"7c430f178aefdf1487fee7144e9641e2"),
|
||||||
("C9FFDEE7788EFB4EC9", "e0841a231ab698db30c6c0f3f246c014"),
|
("C53B777F1C",
|
||||||
("66AC4B7EBA95E53DC10B", "a3b3cea71910d9af56742aa0bb2fe329"),
|
"75ef141d64cb37ec423da2d9d440c925"),
|
||||||
("A510CD18F7A56852EB0319", "577e216843dd11573574d3fb209b97d8"),
|
("89D5B576327B",
|
||||||
("AAED18DBE8938C19ED734A8D", "6f80fb775f27e0a4ce5c2f42fc72c5f1")
|
"ebbaf15eb0ed784c6faa9dc32831bf33"),
|
||||||
];
|
("5D4CCE781EB190",
|
||||||
|
"ce175c4b08172019f05e6b5279889f2c"),
|
||||||
|
("81901FE94932D7B9",
|
||||||
|
"cd4d2f62b8cdb3a0cf968a735a239281"),
|
||||||
|
("C9FFDEE7788EFB4EC9",
|
||||||
|
"e0841a231ab698db30c6c0f3f246c014"),
|
||||||
|
("66AC4B7EBA95E53DC10B",
|
||||||
|
"a3b3cea71910d9af56742aa0bb2fe329"),
|
||||||
|
("A510CD18F7A56852EB0319",
|
||||||
|
"577e216843dd11573574d3fb209b97d8"),
|
||||||
|
("AAED18DBE8938C19ED734A8D",
|
||||||
|
"6f80fb775f27e0a4ce5c2f42fc72c5f1")];
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_md5() {
|
fn test_md5() {
|
||||||
|
|
@ -305,9 +327,7 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_sha1() {
|
fn test_sha1() {
|
||||||
let tests = [
|
let tests = [("616263", "a9993e364706816aba3e25717850c26c9cd0d89d")];
|
||||||
("616263", "a9993e364706816aba3e25717850c26c9cd0d89d"),
|
|
||||||
];
|
|
||||||
|
|
||||||
for test in tests.iter() {
|
for test in tests.iter() {
|
||||||
hash_test(Type::SHA1, test);
|
hash_test(Type::SHA1, test);
|
||||||
|
|
@ -316,9 +336,8 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_sha256() {
|
fn test_sha256() {
|
||||||
let tests = [
|
let tests = [("616263",
|
||||||
("616263", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")];
|
||||||
];
|
|
||||||
|
|
||||||
for test in tests.iter() {
|
for test in tests.iter() {
|
||||||
hash_test(Type::SHA256, test);
|
hash_test(Type::SHA256, test);
|
||||||
|
|
@ -327,9 +346,7 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ripemd160() {
|
fn test_ripemd160() {
|
||||||
let tests = [
|
let tests = [("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")];
|
||||||
("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")
|
|
||||||
];
|
|
||||||
|
|
||||||
for test in tests.iter() {
|
for test in tests.iter() {
|
||||||
hash_test(Type::RIPEMD160, test);
|
hash_test(Type::RIPEMD160, test);
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,17 @@
|
||||||
/*
|
// Copyright 2013 Jack Lloyd
|
||||||
* Copyright 2013 Jack Lloyd
|
//
|
||||||
*
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
// you may not use this file except in compliance with the License.
|
||||||
* you may not use this file except in compliance with the License.
|
// You may obtain a copy of the License at
|
||||||
* You may obtain a copy of the License at
|
//
|
||||||
*
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
//
|
||||||
*
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// See the License for the specific language governing permissions and
|
||||||
* See the License for the specific language governing permissions and
|
// limitations under the License.
|
||||||
* limitations under the License.
|
//
|
||||||
*/
|
|
||||||
|
|
||||||
use libc::{c_int, c_uint};
|
use libc::{c_int, c_uint};
|
||||||
use std::iter::repeat;
|
use std::iter::repeat;
|
||||||
|
|
@ -81,7 +80,11 @@ impl HMAC {
|
||||||
};
|
};
|
||||||
let md = ty.evp_md();
|
let md = ty.evp_md();
|
||||||
|
|
||||||
let mut h = HMAC { ctx: ctx, type_: ty, state: Finalized };
|
let mut h = HMAC {
|
||||||
|
ctx: ctx,
|
||||||
|
type_: ty,
|
||||||
|
state: Finalized,
|
||||||
|
};
|
||||||
h.init_once(md, key);
|
h.init_once(md, key);
|
||||||
h
|
h
|
||||||
}
|
}
|
||||||
|
|
@ -92,7 +95,8 @@ impl HMAC {
|
||||||
let r = ffi_extras::HMAC_Init_ex(&mut self.ctx,
|
let r = ffi_extras::HMAC_Init_ex(&mut self.ctx,
|
||||||
key.as_ptr(),
|
key.as_ptr(),
|
||||||
key.len() as c_int,
|
key.len() as c_int,
|
||||||
md, 0 as *const _);
|
md,
|
||||||
|
0 as *const _);
|
||||||
assert_eq!(r, 1);
|
assert_eq!(r, 1);
|
||||||
}
|
}
|
||||||
self.state = Reset;
|
self.state = Reset;
|
||||||
|
|
@ -102,15 +106,19 @@ impl HMAC {
|
||||||
fn init(&mut self) {
|
fn init(&mut self) {
|
||||||
match self.state {
|
match self.state {
|
||||||
Reset => return,
|
Reset => return,
|
||||||
Updated => { self.finalize(); },
|
Updated => {
|
||||||
|
self.finalize();
|
||||||
|
}
|
||||||
Finalized => (),
|
Finalized => (),
|
||||||
}
|
}
|
||||||
// If the key and/or md is not supplied it's reused from the last time
|
// If the key and/or md is not supplied it's reused from the last time
|
||||||
// avoiding redundant initializations
|
// avoiding redundant initializations
|
||||||
unsafe {
|
unsafe {
|
||||||
let r = ffi_extras::HMAC_Init_ex(&mut self.ctx,
|
let r = ffi_extras::HMAC_Init_ex(&mut self.ctx,
|
||||||
0 as *const _, 0,
|
0 as *const _,
|
||||||
0 as *const _, 0 as *const _);
|
0,
|
||||||
|
0 as *const _,
|
||||||
|
0 as *const _);
|
||||||
assert_eq!(r, 1);
|
assert_eq!(r, 1);
|
||||||
}
|
}
|
||||||
self.state = Reset;
|
self.state = Reset;
|
||||||
|
|
@ -173,7 +181,11 @@ impl Clone for HMAC {
|
||||||
let r = ffi_extras::HMAC_CTX_copy(&mut ctx, &self.ctx);
|
let r = ffi_extras::HMAC_CTX_copy(&mut ctx, &self.ctx);
|
||||||
assert_eq!(r, 1);
|
assert_eq!(r, 1);
|
||||||
}
|
}
|
||||||
HMAC { ctx: ctx, type_: self.type_, state: self.state }
|
HMAC {
|
||||||
|
ctx: ctx,
|
||||||
|
type_: self.type_,
|
||||||
|
state: self.state,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -221,43 +233,45 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hmac_md5() {
|
fn test_hmac_md5() {
|
||||||
// test vectors from RFC 2202
|
// test vectors from RFC 2202
|
||||||
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 7] = [
|
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 7] =
|
||||||
(repeat(0x0b_u8).take(16).collect(), b"Hi There".to_vec(),
|
[(repeat(0x0b_u8).take(16).collect(),
|
||||||
"9294727a3638bb1c13f48ef8158bfc9d".from_hex().unwrap()),
|
b"Hi There".to_vec(),
|
||||||
(b"Jefe".to_vec(),
|
"9294727a3638bb1c13f48ef8158bfc9d".from_hex().unwrap()),
|
||||||
b"what do ya want for nothing?".to_vec(),
|
(b"Jefe".to_vec(),
|
||||||
"750c783e6ab0b503eaa86e310a5db738".from_hex().unwrap()),
|
b"what do ya want for nothing?".to_vec(),
|
||||||
(repeat(0xaa_u8).take(16).collect(), repeat(0xdd_u8).take(50).collect(),
|
"750c783e6ab0b503eaa86e310a5db738".from_hex().unwrap()),
|
||||||
"56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()),
|
(repeat(0xaa_u8).take(16).collect(),
|
||||||
("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
|
repeat(0xdd_u8).take(50).collect(),
|
||||||
repeat(0xcd_u8).take(50).collect(),
|
"56be34521d144c88dbb8c733f0e8b3f6".from_hex().unwrap()),
|
||||||
"697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()),
|
("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
|
||||||
(repeat(0x0c_u8).take(16).collect(),
|
repeat(0xcd_u8).take(50).collect(),
|
||||||
b"Test With Truncation".to_vec(),
|
"697eaf0aca3a3aea3a75164746ffaa79".from_hex().unwrap()),
|
||||||
"56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()),
|
(repeat(0x0c_u8).take(16).collect(),
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
b"Test With Truncation".to_vec(),
|
||||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
"56461ef2342edc00f9bab995690efd4c".from_hex().unwrap()),
|
||||||
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
|
(repeat(0xaa_u8).take(80).collect(),
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||||
b"Test Using Larger Than Block-Size Key \
|
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
|
||||||
and Larger Than One Block-Size Data".to_vec(),
|
(repeat(0xaa_u8).take(80).collect(),
|
||||||
"6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())
|
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_hmac(MD5, &tests);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hmac_md5_recycle() {
|
fn test_hmac_md5_recycle() {
|
||||||
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] = [
|
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] =
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
[(repeat(0xaa_u8).take(80).collect(),
|
||||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||||
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
|
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
(repeat(0xaa_u8).take(80).collect(),
|
||||||
b"Test Using Larger Than Block-Size Key \
|
b"Test Using Larger Than Block-Size Key \
|
||||||
and Larger Than One Block-Size Data".to_vec(),
|
and Larger Than One Block-Size Data"
|
||||||
"6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())
|
.to_vec(),
|
||||||
];
|
"6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())];
|
||||||
|
|
||||||
let mut h = HMAC::new(MD5, &*tests[0].0);
|
let mut h = HMAC::new(MD5, &*tests[0].0);
|
||||||
for i in 0..100usize {
|
for i in 0..100usize {
|
||||||
|
|
@ -283,15 +297,15 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_clone() {
|
fn test_clone() {
|
||||||
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] = [
|
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] =
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
[(repeat(0xaa_u8).take(80).collect(),
|
||||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||||
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
|
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
(repeat(0xaa_u8).take(80).collect(),
|
||||||
b"Test Using Larger Than Block-Size Key \
|
b"Test Using Larger Than Block-Size Key \
|
||||||
and Larger Than One Block-Size Data".to_vec(),
|
and Larger Than One Block-Size Data"
|
||||||
"6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap()),
|
.to_vec(),
|
||||||
];
|
"6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())];
|
||||||
let p = tests[0].0.len() / 2;
|
let p = tests[0].0.len() / 2;
|
||||||
let h0 = HMAC::new(Type::MD5, &*tests[0].0);
|
let h0 = HMAC::new(Type::MD5, &*tests[0].0);
|
||||||
|
|
||||||
|
|
@ -319,43 +333,45 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hmac_sha1() {
|
fn test_hmac_sha1() {
|
||||||
// test vectors from RFC 2202
|
// test vectors from RFC 2202
|
||||||
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 7] = [
|
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 7] =
|
||||||
(repeat(0x0b_u8).take(20).collect(), b"Hi There".to_vec(),
|
[(repeat(0x0b_u8).take(20).collect(),
|
||||||
"b617318655057264e28bc0b6fb378c8ef146be00".from_hex().unwrap()),
|
b"Hi There".to_vec(),
|
||||||
(b"Jefe".to_vec(),
|
"b617318655057264e28bc0b6fb378c8ef146be00".from_hex().unwrap()),
|
||||||
b"what do ya want for nothing?".to_vec(),
|
(b"Jefe".to_vec(),
|
||||||
"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".from_hex().unwrap()),
|
b"what do ya want for nothing?".to_vec(),
|
||||||
(repeat(0xaa_u8).take(20).collect(), repeat(0xdd_u8).take(50).collect(),
|
"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".from_hex().unwrap()),
|
||||||
"125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()),
|
(repeat(0xaa_u8).take(20).collect(),
|
||||||
("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
|
repeat(0xdd_u8).take(50).collect(),
|
||||||
repeat(0xcd_u8).take(50).collect(),
|
"125d7342b9ac11cd91a39af48aa17b4f63f175d3".from_hex().unwrap()),
|
||||||
"4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()),
|
("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
|
||||||
(repeat(0x0c_u8).take(20).collect(),
|
repeat(0xcd_u8).take(50).collect(),
|
||||||
b"Test With Truncation".to_vec(),
|
"4c9007f4026250c6bc8414f9bf50c86c2d7235da".from_hex().unwrap()),
|
||||||
"4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()),
|
(repeat(0x0c_u8).take(20).collect(),
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
b"Test With Truncation".to_vec(),
|
||||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
"4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".from_hex().unwrap()),
|
||||||
"aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()),
|
(repeat(0xaa_u8).take(80).collect(),
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||||
b"Test Using Larger Than Block-Size Key \
|
"aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()),
|
||||||
and Larger Than One Block-Size Data".to_vec(),
|
(repeat(0xaa_u8).take(80).collect(),
|
||||||
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())
|
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_hmac(SHA1, &tests);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hmac_sha1_recycle() {
|
fn test_hmac_sha1_recycle() {
|
||||||
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] = [
|
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] =
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
[(repeat(0xaa_u8).take(80).collect(),
|
||||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||||
"aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()),
|
"aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()),
|
||||||
(repeat(0xaa_u8).take(80).collect(),
|
(repeat(0xaa_u8).take(80).collect(),
|
||||||
b"Test Using Larger Than Block-Size Key \
|
b"Test Using Larger Than Block-Size Key \
|
||||||
and Larger Than One Block-Size Data".to_vec(),
|
and Larger Than One Block-Size Data"
|
||||||
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())
|
.to_vec(),
|
||||||
];
|
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())];
|
||||||
|
|
||||||
let mut h = HMAC::new(SHA1, &*tests[0].0);
|
let mut h = HMAC::new(SHA1, &*tests[0].0);
|
||||||
for i in 0..100usize {
|
for i in 0..100usize {
|
||||||
|
|
@ -368,20 +384,20 @@ mod tests {
|
||||||
|
|
||||||
fn test_sha2(ty: Type, results: &[Vec<u8>]) {
|
fn test_sha2(ty: Type, results: &[Vec<u8>]) {
|
||||||
// test vectors from RFC 4231
|
// test vectors from RFC 4231
|
||||||
let tests: [(Vec<u8>, Vec<u8>); 6] = [
|
let tests: [(Vec<u8>, Vec<u8>); 6] =
|
||||||
(repeat(0xb_u8).take(20).collect(), b"Hi There".to_vec()),
|
[(repeat(0xb_u8).take(20).collect(), b"Hi There".to_vec()),
|
||||||
(b"Jefe".to_vec(),
|
(b"Jefe".to_vec(), b"what do ya want for nothing?".to_vec()),
|
||||||
b"what do ya want for nothing?".to_vec()),
|
(repeat(0xaa_u8).take(20).collect(),
|
||||||
(repeat(0xaa_u8).take(20).collect(), repeat(0xdd_u8).take(50).collect()),
|
repeat(0xdd_u8).take(50).collect()),
|
||||||
("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
|
("0102030405060708090a0b0c0d0e0f10111213141516171819".from_hex().unwrap(),
|
||||||
repeat(0xcd_u8).take(50).collect()),
|
repeat(0xcd_u8).take(50).collect()),
|
||||||
(repeat(0xaa_u8).take(131).collect(),
|
(repeat(0xaa_u8).take(131).collect(),
|
||||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec()),
|
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec()),
|
||||||
(repeat(0xaa_u8).take(131).collect(),
|
(repeat(0xaa_u8).take(131).collect(),
|
||||||
b"This is a test using a larger than block-size key and a \
|
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 \
|
larger than block-size data. The key needs to be hashed \
|
||||||
before being used by the HMAC algorithm.".to_vec())
|
before being used by the HMAC algorithm."
|
||||||
];
|
.to_vec())];
|
||||||
|
|
||||||
for (&(ref key, ref data), res) in tests.iter().zip(results.iter()) {
|
for (&(ref key, ref data), res) in tests.iter().zip(results.iter()) {
|
||||||
assert_eq!(hmac(ty, &**key, &**data), *res);
|
assert_eq!(hmac(ty, &**key, &**data), *res);
|
||||||
|
|
@ -398,83 +414,105 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hmac_sha224() {
|
fn test_hmac_sha224() {
|
||||||
let results = [
|
let results = ["896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22"
|
||||||
"896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22".from_hex().unwrap(),
|
.from_hex()
|
||||||
"a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44".from_hex().unwrap(),
|
.unwrap(),
|
||||||
"7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea".from_hex().unwrap(),
|
"a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44"
|
||||||
"6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a".from_hex().unwrap(),
|
.from_hex()
|
||||||
"95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e".from_hex().unwrap(),
|
.unwrap(),
|
||||||
"3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1".from_hex().unwrap()
|
"7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea"
|
||||||
];
|
.from_hex()
|
||||||
|
.unwrap(),
|
||||||
|
"6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a"
|
||||||
|
.from_hex()
|
||||||
|
.unwrap(),
|
||||||
|
"95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e"
|
||||||
|
.from_hex()
|
||||||
|
.unwrap(),
|
||||||
|
"3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1"
|
||||||
|
.from_hex()
|
||||||
|
.unwrap()];
|
||||||
test_sha2(SHA224, &results);
|
test_sha2(SHA224, &results);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hmac_sha256() {
|
fn test_hmac_sha256() {
|
||||||
let results = [
|
let results = ["b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
|
||||||
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7".from_hex().unwrap(),
|
.from_hex()
|
||||||
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843".from_hex().unwrap(),
|
.unwrap(),
|
||||||
"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe".from_hex().unwrap(),
|
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
|
||||||
"82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b".from_hex().unwrap(),
|
.from_hex()
|
||||||
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54".from_hex().unwrap(),
|
.unwrap(),
|
||||||
"9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2".from_hex().unwrap()
|
"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"
|
||||||
];
|
.from_hex()
|
||||||
|
.unwrap(),
|
||||||
|
"82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"
|
||||||
|
.from_hex()
|
||||||
|
.unwrap(),
|
||||||
|
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"
|
||||||
|
.from_hex()
|
||||||
|
.unwrap(),
|
||||||
|
"9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"
|
||||||
|
.from_hex()
|
||||||
|
.unwrap()];
|
||||||
test_sha2(SHA256, &results);
|
test_sha2(SHA256, &results);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hmac_sha384() {
|
fn test_hmac_sha384() {
|
||||||
let results = [
|
let results = ["afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea90\
|
||||||
"afd03944d84895626b0825f4ab46907f\
|
76ede7f4af152e8b2fa9cb6"
|
||||||
15f9dadbe4101ec682aa034c7cebc59c\
|
.from_hex()
|
||||||
faea9ea9076ede7f4af152e8b2fa9cb6".from_hex().unwrap(),
|
.unwrap(),
|
||||||
"af45d2e376484031617f78d2b58a6b1b\
|
"af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5\
|
||||||
9c7ef464f5a01b47e42ec3736322445e\
|
e69e2c78b3239ecfab21649"
|
||||||
8e2240ca5e69e2c78b3239ecfab21649".from_hex().unwrap(),
|
.from_hex()
|
||||||
"88062608d3e6ad8a0aa2ace014c8a86f\
|
.unwrap(),
|
||||||
0aa635d947ac9febe83ef4e55966144b\
|
"88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e55966144b2a5ab39dc\
|
||||||
2a5ab39dc13814b94e3ab6e101a34f27".from_hex().unwrap(),
|
13814b94e3ab6e101a34f27"
|
||||||
"3e8a69b7783c25851933ab6290af6ca7\
|
.from_hex()
|
||||||
7a9981480850009cc5577c6e1f573b4e\
|
.unwrap(),
|
||||||
6801dd23c4a7d679ccf8a386c674cffb".from_hex().unwrap(),
|
"3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e1f573b4e6801dd23c\
|
||||||
"4ece084485813e9088d2c63a041bc5b4\
|
4a7d679ccf8a386c674cffb"
|
||||||
4f9ef1012a2b588f3cd11f05033ac4c6\
|
.from_hex()
|
||||||
0c2ef6ab4030fe8296248df163f44952".from_hex().unwrap(),
|
.unwrap(),
|
||||||
"6617178e941f020d351e2f254e8fd32c\
|
"4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4\
|
||||||
602420feb0b8fb9adccebb82461e99c5\
|
030fe8296248df163f44952"
|
||||||
a678cc31e799176d3860e6110c46523e".from_hex().unwrap()
|
.from_hex()
|
||||||
];
|
.unwrap(),
|
||||||
|
"6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5a678cc31e\
|
||||||
|
799176d3860e6110c46523e"
|
||||||
|
.from_hex()
|
||||||
|
.unwrap()];
|
||||||
test_sha2(SHA384, &results);
|
test_sha2(SHA384, &results);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_hmac_sha512() {
|
fn test_hmac_sha512() {
|
||||||
let results = [
|
let results = ["87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d\
|
||||||
"87aa7cdea5ef619d4ff0b4241a1d6cb0\
|
6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"
|
||||||
2379f4e2ce4ec2787ad0b30545e17cde\
|
.from_hex()
|
||||||
daa833b7d6b8a702038b274eaea3f4e4\
|
.unwrap(),
|
||||||
be9d914eeb61f1702e696c203a126854".from_hex().unwrap(),
|
"164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c\
|
||||||
"164b7a7bfcf819e2e395fbe73b56e0a3\
|
05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"
|
||||||
87bd64222e831fd610270cd7ea250554\
|
.from_hex()
|
||||||
9758bf75c05a994a6d034f65f8f0e6fd\
|
.unwrap(),
|
||||||
caeab1a34d4a6b4b636e070a38bce737".from_hex().unwrap(),
|
"fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e84827\
|
||||||
"fa73b0089d56a284efb0f0756c890be9\
|
9a722c806b485a47e67c807b946a337bee8942674278859e13292fb"
|
||||||
b1b5dbdd8ee81a3655f83e33b2279d39\
|
.from_hex()
|
||||||
bf3e848279a722c806b485a47e67c807\
|
.unwrap(),
|
||||||
b946a337bee8942674278859e13292fb".from_hex().unwrap(),
|
"b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11\
|
||||||
"b0ba465637458c6990e5a8c5f61d4af7\
|
aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd"
|
||||||
e576d97ff94b872de76f8050361ee3db\
|
.from_hex()
|
||||||
a91ca5c11aa25eb4d679275cc5788063\
|
.unwrap(),
|
||||||
a5f19741120c4f2de2adebeb10a298dd".from_hex().unwrap(),
|
"80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e\
|
||||||
"80b24263c7c1a3ebb71493c1dd7be8b4\
|
05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"
|
||||||
9b46d1f41b4aeec1121b013783f8f352\
|
.from_hex()
|
||||||
6b56d037e05f2598bd0fd2215d6a1e52\
|
.unwrap(),
|
||||||
95e64f73f63f0aec8b915a985d786598".from_hex().unwrap(),
|
"e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3\
|
||||||
"e37b6a775dc87dbaa4dfa9f96e5e3ffd\
|
c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58"
|
||||||
debd71f8867289865df5a32d20cdc944\
|
.from_hex()
|
||||||
b6022cac3c4982b10d5eeb55c3e4de15\
|
.unwrap()];
|
||||||
134676fb6de0446065c97440fa8c6a58".from_hex().unwrap()
|
|
||||||
];
|
|
||||||
test_sha2(SHA512, &results);
|
test_sha2(SHA512, &results);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,18 @@
|
||||||
/*
|
// Copyright 2011 Google Inc.
|
||||||
* Copyright 2011 Google Inc.
|
// 2013 Jack Lloyd
|
||||||
* 2013 Jack Lloyd
|
//
|
||||||
*
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
// you may not use this file except in compliance with the License.
|
||||||
* you may not use this file except in compliance with the License.
|
// You may obtain a copy of the License at
|
||||||
* You may obtain a copy of the License at
|
//
|
||||||
*
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
//
|
||||||
*
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
// See the License for the specific language governing permissions and
|
||||||
* See the License for the specific language governing permissions and
|
// limitations under the License.
|
||||||
* limitations under the License.
|
//
|
||||||
*/
|
|
||||||
|
|
||||||
pub mod hash;
|
pub mod hash;
|
||||||
pub mod hmac;
|
pub mod hmac;
|
||||||
|
|
@ -23,4 +22,4 @@ pub mod rand;
|
||||||
pub mod symm;
|
pub mod symm;
|
||||||
pub mod memcmp;
|
pub mod memcmp;
|
||||||
|
|
||||||
mod symm_internal;
|
mod symm_internal;
|
||||||
|
|
|
||||||
|
|
@ -7,10 +7,9 @@ use crypto::symm;
|
||||||
use ffi;
|
use ffi;
|
||||||
|
|
||||||
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
|
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
|
||||||
pub struct KeyIvPair
|
pub struct KeyIvPair {
|
||||||
{
|
|
||||||
pub key: Vec<u8>,
|
pub key: Vec<u8>,
|
||||||
pub iv: Vec<u8>
|
pub iv: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Derives a key and an IV from various parameters.
|
/// Derives a key and an IV from various parameters.
|
||||||
|
|
@ -23,9 +22,12 @@ pub struct KeyIvPair
|
||||||
///
|
///
|
||||||
/// New applications should not use this and instead use `pbkdf2_hmac_sha1` or
|
/// New applications should not use this and instead use `pbkdf2_hmac_sha1` or
|
||||||
/// another more modern key derivation algorithm.
|
/// another more modern key derivation algorithm.
|
||||||
pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type, message_digest_type: hash::Type,
|
pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type,
|
||||||
data: &[u8], salt: Option<&[u8]>,
|
message_digest_type: hash::Type,
|
||||||
count: u32) -> KeyIvPair {
|
data: &[u8],
|
||||||
|
salt: Option<&[u8]>,
|
||||||
|
count: u32)
|
||||||
|
-> KeyIvPair {
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
|
|
||||||
|
|
@ -33,8 +35,8 @@ pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type, message_digest_type:
|
||||||
Some(salt) => {
|
Some(salt) => {
|
||||||
assert_eq!(salt.len(), ffi::PKCS5_SALT_LEN as usize);
|
assert_eq!(salt.len(), ffi::PKCS5_SALT_LEN as usize);
|
||||||
salt.as_ptr()
|
salt.as_ptr()
|
||||||
},
|
}
|
||||||
None => null()
|
None => null(),
|
||||||
};
|
};
|
||||||
|
|
||||||
ffi::init();
|
ffi::init();
|
||||||
|
|
@ -56,11 +58,8 @@ pub fn evp_bytes_to_key_pbkdf1_compatible(typ: symm::Type, message_digest_type:
|
||||||
key.as_mut_ptr(),
|
key.as_mut_ptr(),
|
||||||
iv.as_mut_ptr());
|
iv.as_mut_ptr());
|
||||||
assert!(ret == keylen as c_int);
|
assert!(ret == keylen as c_int);
|
||||||
|
|
||||||
KeyIvPair {
|
KeyIvPair { key: key, iv: iv }
|
||||||
key: key,
|
|
||||||
iv: iv
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -74,13 +73,17 @@ pub fn pbkdf2_hmac_sha1(pass: &str, salt: &[u8], iter: usize, keylen: usize) ->
|
||||||
|
|
||||||
ffi::init();
|
ffi::init();
|
||||||
|
|
||||||
let r = ffi::PKCS5_PBKDF2_HMAC_SHA1(
|
let r = ffi::PKCS5_PBKDF2_HMAC_SHA1(pass.as_ptr(),
|
||||||
pass.as_ptr(), pass.len() as c_int,
|
pass.len() as c_int,
|
||||||
salt.as_ptr(), salt.len() as c_int,
|
salt.as_ptr(),
|
||||||
iter as c_int, keylen as c_int,
|
salt.len() as c_int,
|
||||||
out.as_mut_ptr());
|
iter as c_int,
|
||||||
|
keylen as c_int,
|
||||||
|
out.as_mut_ptr());
|
||||||
|
|
||||||
if r != 1 { panic!(); }
|
if r != 1 {
|
||||||
|
panic!();
|
||||||
|
}
|
||||||
|
|
||||||
out.set_len(keylen);
|
out.set_len(keylen);
|
||||||
|
|
||||||
|
|
@ -102,7 +105,12 @@ pub fn pbkdf2_hmac_sha512(pass: &str, salt: &[u8], iter: usize, keylen: usize) -
|
||||||
|
|
||||||
/// Derives a key from a password and salt using the PBKDF2-HMAC algorithm with a digest function.
|
/// Derives a key from a password and salt using the PBKDF2-HMAC algorithm with a digest function.
|
||||||
#[cfg(feature = "pkcs5_pbkdf2_hmac")]
|
#[cfg(feature = "pkcs5_pbkdf2_hmac")]
|
||||||
fn pbkdf2_hmac_sha(pass: &str, salt: &[u8], iter: usize, digest: *const ffi::EVP_MD, keylen: usize) -> Vec<u8> {
|
fn pbkdf2_hmac_sha(pass: &str,
|
||||||
|
salt: &[u8],
|
||||||
|
iter: usize,
|
||||||
|
digest: *const ffi::EVP_MD,
|
||||||
|
keylen: usize)
|
||||||
|
-> Vec<u8> {
|
||||||
unsafe {
|
unsafe {
|
||||||
assert!(iter >= 1);
|
assert!(iter >= 1);
|
||||||
assert!(keylen >= 1);
|
assert!(keylen >= 1);
|
||||||
|
|
@ -111,13 +119,18 @@ fn pbkdf2_hmac_sha(pass: &str, salt: &[u8], iter: usize, digest: *const ffi::EVP
|
||||||
|
|
||||||
ffi::init();
|
ffi::init();
|
||||||
|
|
||||||
let r = ffi::PKCS5_PBKDF2_HMAC(
|
let r = ffi::PKCS5_PBKDF2_HMAC(pass.as_ptr(),
|
||||||
pass.as_ptr(), pass.len() as c_int,
|
pass.len() as c_int,
|
||||||
salt.as_ptr(), salt.len() as c_int,
|
salt.as_ptr(),
|
||||||
iter as c_int, digest, keylen as c_int,
|
salt.len() as c_int,
|
||||||
out.as_mut_ptr());
|
iter as c_int,
|
||||||
|
digest,
|
||||||
|
keylen as c_int,
|
||||||
|
out.as_mut_ptr());
|
||||||
|
|
||||||
if r != 1 { panic!(); }
|
if r != 1 {
|
||||||
|
panic!();
|
||||||
|
}
|
||||||
|
|
||||||
out.set_len(keylen);
|
out.set_len(keylen);
|
||||||
|
|
||||||
|
|
@ -134,90 +147,38 @@ mod tests {
|
||||||
// http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06
|
// http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06
|
||||||
#[test]
|
#[test]
|
||||||
fn test_pbkdf2_hmac_sha1() {
|
fn test_pbkdf2_hmac_sha1() {
|
||||||
assert_eq!(
|
assert_eq!(super::pbkdf2_hmac_sha1("password", "salt".as_bytes(), 1, 20),
|
||||||
super::pbkdf2_hmac_sha1(
|
vec![0x0c_u8, 0x60_u8, 0xc8_u8, 0x0f_u8, 0x96_u8, 0x1f_u8, 0x0e_u8, 0x71_u8,
|
||||||
"password",
|
0xf3_u8, 0xa9_u8, 0xb5_u8, 0x24_u8, 0xaf_u8, 0x60_u8, 0x12_u8, 0x06_u8,
|
||||||
"salt".as_bytes(),
|
0x2f_u8, 0xe0_u8, 0x37_u8, 0xa6_u8]);
|
||||||
1,
|
|
||||||
20
|
|
||||||
),
|
|
||||||
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!(
|
assert_eq!(super::pbkdf2_hmac_sha1("password", "salt".as_bytes(), 2, 20),
|
||||||
super::pbkdf2_hmac_sha1(
|
vec![0xea_u8, 0x6c_u8, 0x01_u8, 0x4d_u8, 0xc7_u8, 0x2d_u8, 0x6f_u8, 0x8c_u8,
|
||||||
"password",
|
0xcd_u8, 0x1e_u8, 0xd9_u8, 0x2a_u8, 0xce_u8, 0x1d_u8, 0x41_u8, 0xf0_u8,
|
||||||
"salt".as_bytes(),
|
0xd8_u8, 0xde_u8, 0x89_u8, 0x57_u8]);
|
||||||
2,
|
|
||||||
20
|
|
||||||
),
|
|
||||||
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!(
|
assert_eq!(super::pbkdf2_hmac_sha1("password", "salt".as_bytes(), 4096, 20),
|
||||||
super::pbkdf2_hmac_sha1(
|
vec![0x4b_u8, 0x00_u8, 0x79_u8, 0x01_u8, 0xb7_u8, 0x65_u8, 0x48_u8, 0x9a_u8,
|
||||||
"password",
|
0xbe_u8, 0xad_u8, 0x49_u8, 0xd9_u8, 0x26_u8, 0xf7_u8, 0x21_u8, 0xd0_u8,
|
||||||
"salt".as_bytes(),
|
0x65_u8, 0xa4_u8, 0x29_u8, 0xc1_u8]);
|
||||||
4096,
|
|
||||||
20
|
|
||||||
),
|
|
||||||
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!(
|
assert_eq!(super::pbkdf2_hmac_sha1("password", "salt".as_bytes(), 16777216, 20),
|
||||||
super::pbkdf2_hmac_sha1(
|
vec![0xee_u8, 0xfe_u8, 0x3d_u8, 0x61_u8, 0xcd_u8, 0x4d_u8, 0xa4_u8, 0xe4_u8,
|
||||||
"password",
|
0xe9_u8, 0x94_u8, 0x5b_u8, 0x3d_u8, 0x6b_u8, 0xa2_u8, 0x15_u8, 0x8c_u8,
|
||||||
"salt".as_bytes(),
|
0x26_u8, 0x34_u8, 0xe9_u8, 0x84_u8]);
|
||||||
16777216,
|
|
||||||
20
|
|
||||||
),
|
|
||||||
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!(
|
assert_eq!(super::pbkdf2_hmac_sha1("passwordPASSWORDpassword",
|
||||||
super::pbkdf2_hmac_sha1(
|
"saltSALTsaltSALTsaltSALTsaltSALTsalt".as_bytes(),
|
||||||
"passwordPASSWORDpassword",
|
4096,
|
||||||
"saltSALTsaltSALTsaltSALTsaltSALTsalt".as_bytes(),
|
25),
|
||||||
4096,
|
vec![0x3d_u8, 0x2e_u8, 0xec_u8, 0x4f_u8, 0xe4_u8, 0x1c_u8, 0x84_u8, 0x9b_u8,
|
||||||
25
|
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,
|
||||||
vec!(
|
0x38_u8]);
|
||||||
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!(
|
assert_eq!(super::pbkdf2_hmac_sha1("pass\x00word", "sa\x00lt".as_bytes(), 4096, 16),
|
||||||
super::pbkdf2_hmac_sha1(
|
vec![0x56_u8, 0xfa_u8, 0x6a_u8, 0xa7_u8, 0x55_u8, 0x48_u8, 0x09_u8, 0x9d_u8,
|
||||||
"pass\x00word",
|
0xcc_u8, 0x37_u8, 0xd7_u8, 0xf0_u8, 0x34_u8, 0x25_u8, 0xe0_u8, 0xc3_u8]);
|
||||||
"sa\x00lt".as_bytes(),
|
|
||||||
4096,
|
|
||||||
16
|
|
||||||
),
|
|
||||||
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
|
// Test vectors from
|
||||||
|
|
@ -225,33 +186,13 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg(feature = "pkcs5_pbkdf2_hmac")]
|
#[cfg(feature = "pkcs5_pbkdf2_hmac")]
|
||||||
fn test_pbkdf2_hmac_sha256() {
|
fn test_pbkdf2_hmac_sha256() {
|
||||||
assert_eq!(
|
assert_eq!(super::pbkdf2_hmac_sha256("passwd", "salt".as_bytes(), 1, 16),
|
||||||
super::pbkdf2_hmac_sha256(
|
vec![0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8,
|
||||||
"passwd",
|
0xec_u8, 0x16_u8, 0x91_u8, 0xc2_u8, 0x25_u8, 0x44_u8, 0xb6_u8, 0x05_u8]);
|
||||||
"salt".as_bytes(),
|
|
||||||
1,
|
|
||||||
16
|
|
||||||
),
|
|
||||||
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!(
|
assert_eq!(super::pbkdf2_hmac_sha256("Password", "NaCl".as_bytes(), 80000, 16),
|
||||||
super::pbkdf2_hmac_sha256(
|
vec![0x4d_u8, 0xdc_u8, 0xd8_u8, 0xf6_u8, 0x0b_u8, 0x98_u8, 0xbe_u8, 0x21_u8,
|
||||||
"Password",
|
0x83_u8, 0x0c_u8, 0xee_u8, 0x5e_u8, 0xf2_u8, 0x27_u8, 0x01_u8, 0xf9_u8]);
|
||||||
"NaCl".as_bytes(),
|
|
||||||
80000,
|
|
||||||
16
|
|
||||||
),
|
|
||||||
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
|
// Test vectors from
|
||||||
|
|
@ -259,109 +200,67 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg(feature = "pkcs5_pbkdf2_hmac")]
|
#[cfg(feature = "pkcs5_pbkdf2_hmac")]
|
||||||
fn test_pbkdf2_hmac_sha512() {
|
fn test_pbkdf2_hmac_sha512() {
|
||||||
assert_eq!(
|
assert_eq!(super::pbkdf2_hmac_sha512("password", "NaCL".as_bytes(), 1, 64),
|
||||||
super::pbkdf2_hmac_sha512(
|
vec![0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8, 0x4f_u8,
|
||||||
"password",
|
0x94_u8, 0x77_u8, 0x1a_u8, 0x75_u8, 0x73_u8, 0x6b_u8, 0xb8_u8, 0x8b_u8,
|
||||||
"NaCL".as_bytes(),
|
0xd3_u8, 0xc7_u8, 0xb3_u8, 0x82_u8, 0x70_u8, 0xcf_u8, 0xb5_u8, 0x0c_u8,
|
||||||
1,
|
0xb3_u8, 0x90_u8, 0xed_u8, 0x78_u8, 0xb3_u8, 0x05_u8, 0x65_u8, 0x6a_u8,
|
||||||
64
|
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,
|
||||||
vec!(
|
0x60_u8, 0x60_u8, 0xa0_u8, 0x9f_u8, 0x76_u8, 0x41_u8, 0x5e_u8, 0x9f_u8,
|
||||||
0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8,
|
0x71_u8, 0xea_u8, 0x47_u8, 0xf9_u8, 0xe9_u8, 0x06_u8, 0x43_u8, 0x06_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!(
|
assert_eq!(super::pbkdf2_hmac_sha512("pass\0word", "sa\0lt".as_bytes(), 1, 64),
|
||||||
super::pbkdf2_hmac_sha512(
|
vec![0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8, 0x67_u8,
|
||||||
"pass\0word",
|
0x8b_u8, 0xcf_u8, 0xd1_u8, 0x45_u8, 0xf0_u8, 0x9d_u8, 0x83_u8, 0x52_u8,
|
||||||
"sa\0lt".as_bytes(),
|
0x2f_u8, 0x93_u8, 0x36_u8, 0x15_u8, 0x60_u8, 0x56_u8, 0x3c_u8, 0x4d_u8,
|
||||||
1,
|
0x0d_u8, 0x63_u8, 0xb8_u8, 0x83_u8, 0x29_u8, 0x87_u8, 0x10_u8, 0x90_u8,
|
||||||
64
|
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,
|
||||||
vec!(
|
0xb2_u8, 0x0f_u8, 0x06_u8, 0xbc_u8, 0x53_u8, 0x5e_u8, 0x5a_u8, 0xb5_u8,
|
||||||
0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8,
|
0x44_u8, 0x0d_u8, 0xf7_u8, 0xe8_u8, 0x78_u8, 0x29_u8, 0x6f_u8, 0xa7_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!(
|
assert_eq!(super::pbkdf2_hmac_sha512("passwordPASSWORDpassword",
|
||||||
super::pbkdf2_hmac_sha512(
|
"salt\0\0\0".as_bytes(),
|
||||||
"passwordPASSWORDpassword",
|
50,
|
||||||
"salt\0\0\0".as_bytes(),
|
64),
|
||||||
50,
|
vec![0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8, 0x96_u8,
|
||||||
64
|
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,
|
||||||
vec!(
|
0xc8_u8, 0xc9_u8, 0x37_u8, 0x5f_u8, 0x9b_u8, 0xda_u8, 0x1c_u8, 0xcd_u8,
|
||||||
0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8,
|
0x1b_u8, 0x6f_u8, 0x0b_u8, 0x2f_u8, 0xc3_u8, 0xad_u8, 0xda_u8, 0x50_u8,
|
||||||
0x96_u8, 0x85_u8, 0x7f_u8, 0xd2_u8, 0xb9_u8, 0xf8_u8, 0xca_u8,
|
0x54_u8, 0x12_u8, 0xe7_u8, 0x9d_u8, 0x89_u8, 0x00_u8, 0x56_u8, 0xc6_u8,
|
||||||
0x28_u8, 0x02_u8, 0x3b_u8, 0x30_u8, 0xee_u8, 0x2a_u8, 0x39_u8,
|
0x2e_u8, 0x52_u8, 0x4c_u8, 0x7d_u8, 0x51_u8, 0x15_u8, 0x4b_u8, 0x1a_u8,
|
||||||
0xf5_u8, 0xad_u8, 0xca_u8, 0xc8_u8, 0xc9_u8, 0x37_u8, 0x5f_u8,
|
0x85_u8, 0x34_u8, 0x57_u8, 0x5b_u8, 0xd0_u8, 0x2d_u8, 0xee_u8, 0x39_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]
|
#[test]
|
||||||
fn test_evp_bytes_to_key_pbkdf1_compatible() {
|
fn test_evp_bytes_to_key_pbkdf1_compatible() {
|
||||||
let salt = [
|
let salt = [16_u8, 34_u8, 19_u8, 23_u8, 141_u8, 4_u8, 207_u8, 221_u8];
|
||||||
16_u8, 34_u8, 19_u8, 23_u8, 141_u8, 4_u8, 207_u8, 221_u8
|
|
||||||
];
|
|
||||||
|
|
||||||
let data = [
|
let data = [143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8, 241_u8, 242_u8, 31_u8,
|
||||||
143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8,
|
154_u8, 56_u8, 198_u8, 145_u8, 192_u8, 64_u8, 2_u8, 245_u8, 167_u8, 220_u8,
|
||||||
241_u8, 242_u8, 31_u8, 154_u8, 56_u8, 198_u8, 145_u8, 192_u8, 64_u8,
|
55_u8, 119_u8, 233_u8, 136_u8, 139_u8, 27_u8, 71_u8, 242_u8, 119_u8, 175_u8,
|
||||||
2_u8, 245_u8, 167_u8, 220_u8, 55_u8, 119_u8, 233_u8, 136_u8, 139_u8,
|
65_u8, 207_u8];
|
||||||
27_u8, 71_u8, 242_u8, 119_u8, 175_u8, 65_u8, 207_u8
|
|
||||||
];
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
let expected_key = vec![
|
let expected_key = vec![249_u8, 115_u8, 114_u8, 97_u8, 32_u8, 213_u8, 165_u8, 146_u8,
|
||||||
249_u8, 115_u8, 114_u8, 97_u8, 32_u8, 213_u8, 165_u8, 146_u8, 58_u8,
|
58_u8, 87_u8, 234_u8, 3_u8, 43_u8, 250_u8, 97_u8, 114_u8, 26_u8,
|
||||||
87_u8, 234_u8, 3_u8, 43_u8, 250_u8, 97_u8, 114_u8, 26_u8, 98_u8,
|
98_u8, 245_u8, 246_u8, 238_u8, 177_u8, 229_u8, 161_u8, 183_u8,
|
||||||
245_u8, 246_u8, 238_u8, 177_u8, 229_u8, 161_u8, 183_u8, 224_u8,
|
224_u8, 174_u8, 3_u8, 6_u8, 244_u8, 236_u8, 255_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,
|
||||||
let expected_iv = vec![
|
0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8,
|
||||||
4_u8, 223_u8, 153_u8, 219_u8, 28_u8, 142_u8, 234_u8, 68_u8, 227_u8,
|
0_u8, 0_u8, 0_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!(
|
assert_eq!(super::evp_bytes_to_key_pbkdf1_compatible(symm::Type::AES_256_CBC,
|
||||||
super::evp_bytes_to_key_pbkdf1_compatible(
|
hash::Type::SHA1,
|
||||||
symm::Type::AES_256_CBC,
|
&data,
|
||||||
hash::Type::SHA1,
|
Some(&salt),
|
||||||
&data,
|
1),
|
||||||
Some(&salt),
|
super::KeyIvPair {
|
||||||
1
|
key: expected_key,
|
||||||
),
|
iv: expected_iv,
|
||||||
super::KeyIvPair {
|
});
|
||||||
key: expected_key,
|
|
||||||
iv: expected_iv
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ use std::io::prelude::*;
|
||||||
use std::iter::repeat;
|
use std::iter::repeat;
|
||||||
use std::mem;
|
use std::mem;
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
use bio::{MemBio};
|
use bio::MemBio;
|
||||||
use crypto::hash;
|
use crypto::hash;
|
||||||
use crypto::hash::Type as HashType;
|
use crypto::hash::Type as HashType;
|
||||||
use ffi;
|
use ffi;
|
||||||
|
|
@ -14,7 +14,7 @@ use ssl::error::{SslError, StreamError};
|
||||||
pub enum Parts {
|
pub enum Parts {
|
||||||
Neither,
|
Neither,
|
||||||
Public,
|
Public,
|
||||||
Both
|
Both,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Represents a role an asymmetric key might be appropriate for.
|
/// Represents a role an asymmetric key might be appropriate for.
|
||||||
|
|
@ -23,31 +23,31 @@ pub enum Role {
|
||||||
Encrypt,
|
Encrypt,
|
||||||
Decrypt,
|
Decrypt,
|
||||||
Sign,
|
Sign,
|
||||||
Verify
|
Verify,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Type of encryption padding to use.
|
/// Type of encryption padding to use.
|
||||||
#[derive(Copy, Clone)]
|
#[derive(Copy, Clone)]
|
||||||
pub enum EncryptionPadding {
|
pub enum EncryptionPadding {
|
||||||
OAEP,
|
OAEP,
|
||||||
PKCS1v15
|
PKCS1v15,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn openssl_padding_code(padding: EncryptionPadding) -> c_int {
|
fn openssl_padding_code(padding: EncryptionPadding) -> c_int {
|
||||||
match padding {
|
match padding {
|
||||||
EncryptionPadding::OAEP => 4,
|
EncryptionPadding::OAEP => 4,
|
||||||
EncryptionPadding::PKCS1v15 => 1
|
EncryptionPadding::PKCS1v15 => 1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn openssl_hash_nid(hash: HashType) -> c_int {
|
fn openssl_hash_nid(hash: HashType) -> c_int {
|
||||||
match hash {
|
match hash {
|
||||||
HashType::MD5 => 4, // NID_md5,
|
HashType::MD5 => 4, // NID_md5,
|
||||||
HashType::SHA1 => 64, // NID_sha1
|
HashType::SHA1 => 64, // NID_sha1
|
||||||
HashType::SHA224 => 675, // NID_sha224
|
HashType::SHA224 => 675, // NID_sha224
|
||||||
HashType::SHA256 => 672, // NID_sha256
|
HashType::SHA256 => 672, // NID_sha256
|
||||||
HashType::SHA384 => 673, // NID_sha384
|
HashType::SHA384 => 673, // NID_sha384
|
||||||
HashType::SHA512 => 674, // NID_sha512
|
HashType::SHA512 => 674, // NID_sha512
|
||||||
HashType::RIPEMD160 => 117, // NID_ripemd160
|
HashType::RIPEMD160 => 117, // NID_ripemd160
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -81,32 +81,38 @@ impl PKey {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads private key from PEM, takes ownership of handle
|
/// Reads private key from PEM, takes ownership of handle
|
||||||
pub fn private_key_from_pem<R>(reader: &mut R) -> Result<PKey, SslError> where R: Read {
|
pub fn private_key_from_pem<R>(reader: &mut R) -> Result<PKey, SslError>
|
||||||
|
where R: Read
|
||||||
|
{
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.get_handle(),
|
let evp = try_ssl_null!(ffi::PEM_read_bio_PrivateKey(mem_bio.get_handle(),
|
||||||
ptr::null_mut(),
|
ptr::null_mut(),
|
||||||
None, ptr::null_mut()));
|
None,
|
||||||
|
ptr::null_mut()));
|
||||||
Ok(PKey {
|
Ok(PKey {
|
||||||
evp: evp,
|
evp: evp,
|
||||||
parts: Parts::Both,
|
parts: Parts::Both,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads public key from PEM, takes ownership of handle
|
/// Reads public key from PEM, takes ownership of handle
|
||||||
pub fn public_key_from_pem<R>(reader: &mut R) -> Result<PKey, SslError> where R: Read {
|
pub fn public_key_from_pem<R>(reader: &mut R) -> Result<PKey, SslError>
|
||||||
|
where R: Read
|
||||||
|
{
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let evp = try_ssl_null!(ffi::PEM_read_bio_PUBKEY(mem_bio.get_handle(),
|
let evp = try_ssl_null!(ffi::PEM_read_bio_PUBKEY(mem_bio.get_handle(),
|
||||||
ptr::null_mut(),
|
ptr::null_mut(),
|
||||||
None, ptr::null_mut()));
|
None,
|
||||||
|
ptr::null_mut()));
|
||||||
Ok(PKey {
|
Ok(PKey {
|
||||||
evp: evp,
|
evp: evp,
|
||||||
parts: Parts::Public,
|
parts: Parts::Public,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -116,7 +122,9 @@ impl PKey {
|
||||||
unsafe {
|
unsafe {
|
||||||
let rsa = ffi::EVP_PKEY_get1_RSA(self.evp);
|
let rsa = ffi::EVP_PKEY_get1_RSA(self.evp);
|
||||||
let len = f(rsa, ptr::null());
|
let len = f(rsa, ptr::null());
|
||||||
if len < 0 as c_int { return vec!(); }
|
if len < 0 as c_int {
|
||||||
|
return vec![];
|
||||||
|
}
|
||||||
let mut s = repeat(0u8).take(len as usize).collect::<Vec<_>>();
|
let mut s = repeat(0u8).take(len as usize).collect::<Vec<_>>();
|
||||||
|
|
||||||
let r = f(rsa, &s.as_mut_ptr());
|
let r = f(rsa, &s.as_mut_ptr());
|
||||||
|
|
@ -127,14 +135,17 @@ impl PKey {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn _fromstr(&mut self, s: &[u8], f: unsafe extern "C" fn(*const *mut ffi::RSA, *const *const u8, c_uint) -> *mut ffi::RSA) -> bool {
|
fn _fromstr(&mut self,
|
||||||
|
s: &[u8],
|
||||||
|
f: unsafe extern "C" fn(*const *mut ffi::RSA, *const *const u8, c_uint)
|
||||||
|
-> *mut ffi::RSA)
|
||||||
|
-> bool {
|
||||||
unsafe {
|
unsafe {
|
||||||
let rsa = ptr::null_mut();
|
let rsa = ptr::null_mut();
|
||||||
f(&rsa, &s.as_ptr(), s.len() as c_uint);
|
f(&rsa, &s.as_ptr(), s.len() as c_uint);
|
||||||
if !rsa.is_null() {
|
if !rsa.is_null() {
|
||||||
ffi::EVP_PKEY_set1_RSA(self.evp, rsa) == 1
|
ffi::EVP_PKEY_set1_RSA(self.evp, rsa) == 1
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -142,18 +153,13 @@ impl PKey {
|
||||||
|
|
||||||
pub fn gen(&mut self, keysz: usize) {
|
pub fn gen(&mut self, keysz: usize) {
|
||||||
unsafe {
|
unsafe {
|
||||||
let rsa = ffi::RSA_generate_key(
|
let rsa = ffi::RSA_generate_key(keysz as c_int,
|
||||||
keysz as c_int,
|
65537 as c_ulong,
|
||||||
65537 as c_ulong,
|
ptr::null(),
|
||||||
ptr::null(),
|
ptr::null());
|
||||||
ptr::null()
|
|
||||||
);
|
|
||||||
|
|
||||||
// XXX: 6 == NID_rsaEncryption
|
// XXX: 6 == NID_rsaEncryption
|
||||||
ffi::EVP_PKEY_assign(
|
ffi::EVP_PKEY_assign(self.evp, 6 as c_int, mem::transmute(rsa));
|
||||||
self.evp,
|
|
||||||
6 as c_int,
|
|
||||||
mem::transmute(rsa));
|
|
||||||
|
|
||||||
self.parts = Parts::Both;
|
self.parts = Parts::Both;
|
||||||
}
|
}
|
||||||
|
|
@ -194,11 +200,18 @@ impl PKey {
|
||||||
|
|
||||||
/// Stores private key as a PEM
|
/// Stores private key as a PEM
|
||||||
// FIXME: also add password and encryption
|
// FIXME: also add password and encryption
|
||||||
pub fn write_pem<W: Write>(&self, writer: &mut W/*, password: Option<String>*/) -> Result<(), SslError> {
|
pub fn write_pem<W: Write>(&self,
|
||||||
|
writer: &mut W /* , password: Option<String> */)
|
||||||
|
-> Result<(), SslError> {
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
unsafe {
|
unsafe {
|
||||||
try_ssl!(ffi::PEM_write_bio_PrivateKey(mem_bio.get_handle(), self.evp, ptr::null(),
|
try_ssl!(ffi::PEM_write_bio_PrivateKey(mem_bio.get_handle(),
|
||||||
ptr::null_mut(), -1, None, ptr::null_mut()));
|
self.evp,
|
||||||
|
ptr::null(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
-1,
|
||||||
|
None,
|
||||||
|
ptr::null_mut()));
|
||||||
|
|
||||||
}
|
}
|
||||||
let mut buf = vec![];
|
let mut buf = vec![];
|
||||||
|
|
@ -207,11 +220,11 @@ impl PKey {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stores public key as a PEM
|
/// Stores public key as a PEM
|
||||||
pub fn write_pub_pem<W: Write>(&self, writer: &mut W/*, password: Option<String>*/) -> Result<(), SslError> {
|
pub fn write_pub_pem<W: Write>(&self,
|
||||||
|
writer: &mut W /* , password: Option<String> */)
|
||||||
|
-> Result<(), SslError> {
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
unsafe {
|
unsafe { try_ssl!(ffi::PEM_write_bio_PUBKEY(mem_bio.get_handle(), self.evp)) }
|
||||||
try_ssl!(ffi::PEM_write_bio_PUBKEY(mem_bio.get_handle(), self.evp))
|
|
||||||
}
|
|
||||||
let mut buf = vec![];
|
let mut buf = vec![];
|
||||||
try!(mem_bio.read_to_end(&mut buf).map_err(StreamError));
|
try!(mem_bio.read_to_end(&mut buf).map_err(StreamError));
|
||||||
writer.write_all(&buf).map_err(StreamError)
|
writer.write_all(&buf).map_err(StreamError)
|
||||||
|
|
@ -225,8 +238,7 @@ impl PKey {
|
||||||
let rsa = ffi::EVP_PKEY_get1_RSA(self.evp);
|
let rsa = ffi::EVP_PKEY_get1_RSA(self.evp);
|
||||||
if rsa.is_null() {
|
if rsa.is_null() {
|
||||||
0
|
0
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
ffi::RSA_size(rsa) as usize
|
ffi::RSA_size(rsa) as usize
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -237,26 +249,30 @@ impl PKey {
|
||||||
*/
|
*/
|
||||||
pub fn can(&self, r: Role) -> bool {
|
pub fn can(&self, r: Role) -> bool {
|
||||||
match r {
|
match r {
|
||||||
Role::Encrypt =>
|
Role::Encrypt => {
|
||||||
match self.parts {
|
match self.parts {
|
||||||
Parts::Neither => false,
|
Parts::Neither => false,
|
||||||
_ => true,
|
_ => true,
|
||||||
},
|
}
|
||||||
Role::Verify =>
|
}
|
||||||
|
Role::Verify => {
|
||||||
match self.parts {
|
match self.parts {
|
||||||
Parts::Neither => false,
|
Parts::Neither => false,
|
||||||
_ => true,
|
_ => true,
|
||||||
},
|
}
|
||||||
Role::Decrypt =>
|
}
|
||||||
|
Role::Decrypt => {
|
||||||
match self.parts {
|
match self.parts {
|
||||||
Parts::Both => true,
|
Parts::Both => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
},
|
}
|
||||||
Role::Sign =>
|
}
|
||||||
|
Role::Sign => {
|
||||||
match self.parts {
|
match self.parts {
|
||||||
Parts::Both => true,
|
Parts::Both => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
},
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -289,16 +305,15 @@ impl PKey {
|
||||||
|
|
||||||
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
||||||
|
|
||||||
let rv = ffi::RSA_private_encrypt(
|
let rv = ffi::RSA_private_encrypt(s.len() as c_int,
|
||||||
s.len() as c_int,
|
s.as_ptr(),
|
||||||
s.as_ptr(),
|
r.as_mut_ptr(),
|
||||||
r.as_mut_ptr(),
|
rsa,
|
||||||
rsa,
|
openssl_padding_code(padding));
|
||||||
openssl_padding_code(padding));
|
|
||||||
|
|
||||||
if rv < 0 as c_int {
|
if rv < 0 as c_int {
|
||||||
// println!("{:?}", SslError::get());
|
// println!("{:?}", SslError::get());
|
||||||
vec!()
|
vec![]
|
||||||
} else {
|
} else {
|
||||||
r.truncate(rv as usize);
|
r.truncate(rv as usize);
|
||||||
r
|
r
|
||||||
|
|
@ -318,15 +333,14 @@ impl PKey {
|
||||||
|
|
||||||
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
||||||
|
|
||||||
let rv = ffi::RSA_public_encrypt(
|
let rv = ffi::RSA_public_encrypt(s.len() as c_int,
|
||||||
s.len() as c_int,
|
s.as_ptr(),
|
||||||
s.as_ptr(),
|
r.as_mut_ptr(),
|
||||||
r.as_mut_ptr(),
|
rsa,
|
||||||
rsa,
|
openssl_padding_code(padding));
|
||||||
openssl_padding_code(padding));
|
|
||||||
|
|
||||||
if rv < 0 as c_int {
|
if rv < 0 as c_int {
|
||||||
vec!()
|
vec![]
|
||||||
} else {
|
} else {
|
||||||
r.truncate(rv as usize);
|
r.truncate(rv as usize);
|
||||||
r
|
r
|
||||||
|
|
@ -346,15 +360,14 @@ impl PKey {
|
||||||
|
|
||||||
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
||||||
|
|
||||||
let rv = ffi::RSA_private_decrypt(
|
let rv = ffi::RSA_private_decrypt(s.len() as c_int,
|
||||||
s.len() as c_int,
|
s.as_ptr(),
|
||||||
s.as_ptr(),
|
r.as_mut_ptr(),
|
||||||
r.as_mut_ptr(),
|
rsa,
|
||||||
rsa,
|
openssl_padding_code(padding));
|
||||||
openssl_padding_code(padding));
|
|
||||||
|
|
||||||
if rv < 0 as c_int {
|
if rv < 0 as c_int {
|
||||||
vec!()
|
vec![]
|
||||||
} else {
|
} else {
|
||||||
r.truncate(rv as usize);
|
r.truncate(rv as usize);
|
||||||
r
|
r
|
||||||
|
|
@ -374,15 +387,14 @@ impl PKey {
|
||||||
|
|
||||||
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
||||||
|
|
||||||
let rv = ffi::RSA_public_decrypt(
|
let rv = ffi::RSA_public_decrypt(s.len() as c_int,
|
||||||
s.len() as c_int,
|
s.as_ptr(),
|
||||||
s.as_ptr(),
|
r.as_mut_ptr(),
|
||||||
r.as_mut_ptr(),
|
rsa,
|
||||||
rsa,
|
openssl_padding_code(padding));
|
||||||
openssl_padding_code(padding));
|
|
||||||
|
|
||||||
if rv < 0 as c_int {
|
if rv < 0 as c_int {
|
||||||
vec!()
|
vec![]
|
||||||
} else {
|
} else {
|
||||||
r.truncate(rv as usize);
|
r.truncate(rv as usize);
|
||||||
r
|
r
|
||||||
|
|
@ -394,46 +406,62 @@ impl PKey {
|
||||||
* Encrypts data with the public key, using OAEP padding, returning the encrypted data. The
|
* Encrypts data with the public key, using OAEP padding, returning the encrypted data. The
|
||||||
* supplied data must not be larger than max_data().
|
* supplied data must not be larger than max_data().
|
||||||
*/
|
*/
|
||||||
pub fn encrypt(&self, s: &[u8]) -> Vec<u8> { self.public_encrypt_with_padding(s, EncryptionPadding::OAEP) }
|
pub fn encrypt(&self, s: &[u8]) -> Vec<u8> {
|
||||||
|
self.public_encrypt_with_padding(s, EncryptionPadding::OAEP)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encrypts data with the public key, using provided padding, returning the encrypted data. The
|
* Encrypts data with the public key, using provided padding, returning the encrypted data. The
|
||||||
* supplied data must not be larger than max_data().
|
* supplied data must not be larger than max_data().
|
||||||
*/
|
*/
|
||||||
pub fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Vec<u8> { self.public_encrypt_with_padding(s, padding) }
|
pub fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Vec<u8> {
|
||||||
|
self.public_encrypt_with_padding(s, padding)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encrypts data with the public key, using OAEP padding, returning the encrypted data. The
|
* Encrypts data with the public key, using OAEP padding, returning the encrypted data. The
|
||||||
* supplied data must not be larger than max_data().
|
* supplied data must not be larger than max_data().
|
||||||
*/
|
*/
|
||||||
pub fn public_encrypt(&self, s: &[u8]) -> Vec<u8> { self.public_encrypt_with_padding(s, EncryptionPadding::OAEP) }
|
pub fn public_encrypt(&self, s: &[u8]) -> Vec<u8> {
|
||||||
|
self.public_encrypt_with_padding(s, EncryptionPadding::OAEP)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decrypts data with the public key, using PKCS1v15 padding, returning the decrypted data.
|
* Decrypts data with the public key, using PKCS1v15 padding, returning the decrypted data.
|
||||||
*/
|
*/
|
||||||
pub fn public_decrypt(&self, s: &[u8]) -> Vec<u8> { self.public_decrypt_with_padding(s, EncryptionPadding::PKCS1v15) }
|
pub fn public_decrypt(&self, s: &[u8]) -> Vec<u8> {
|
||||||
|
self.public_decrypt_with_padding(s, EncryptionPadding::PKCS1v15)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decrypts data with the private key, expecting OAEP padding, returning the decrypted data.
|
* Decrypts data with the private key, expecting OAEP padding, returning the decrypted data.
|
||||||
*/
|
*/
|
||||||
pub fn decrypt(&self, s: &[u8]) -> Vec<u8> { self.private_decrypt_with_padding(s, EncryptionPadding::OAEP) }
|
pub fn decrypt(&self, s: &[u8]) -> Vec<u8> {
|
||||||
|
self.private_decrypt_with_padding(s, EncryptionPadding::OAEP)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decrypts data with the private key, using provided padding, returning the encrypted data. The
|
* Decrypts data with the private key, using provided padding, returning the encrypted data. The
|
||||||
* supplied data must not be larger than max_data().
|
* supplied data must not be larger than max_data().
|
||||||
*/
|
*/
|
||||||
pub fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Vec<u8> { self.private_decrypt_with_padding(s, padding) }
|
pub fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> Vec<u8> {
|
||||||
|
self.private_decrypt_with_padding(s, padding)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decrypts data with the private key, expecting OAEP padding, returning the decrypted data.
|
* Decrypts data with the private key, expecting OAEP padding, returning the decrypted data.
|
||||||
*/
|
*/
|
||||||
pub fn private_decrypt(&self, s: &[u8]) -> Vec<u8> { self.private_decrypt_with_padding(s, EncryptionPadding::OAEP) }
|
pub fn private_decrypt(&self, s: &[u8]) -> Vec<u8> {
|
||||||
|
self.private_decrypt_with_padding(s, EncryptionPadding::OAEP)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encrypts data with the private key, using PKCS1v15 padding, returning the encrypted data. The
|
* Encrypts data with the private key, using PKCS1v15 padding, returning the encrypted data. The
|
||||||
* supplied data must not be larger than max_data().
|
* supplied data must not be larger than max_data().
|
||||||
*/
|
*/
|
||||||
pub fn private_encrypt(&self, s: &[u8]) -> Vec<u8> { self.private_encrypt_with_padding(s, EncryptionPadding::PKCS1v15) }
|
pub fn private_encrypt(&self, s: &[u8]) -> Vec<u8> {
|
||||||
|
self.private_encrypt_with_padding(s, EncryptionPadding::PKCS1v15)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Signs data, using OpenSSL's default scheme and adding sha256 ASN.1 information to the
|
* Signs data, using OpenSSL's default scheme and adding sha256 ASN.1 information to the
|
||||||
|
|
@ -441,14 +469,18 @@ impl PKey {
|
||||||
* The bytes to sign must be the result of a sha256 hashing;
|
* The bytes to sign must be the result of a sha256 hashing;
|
||||||
* returns the signature.
|
* returns the signature.
|
||||||
*/
|
*/
|
||||||
pub fn sign(&self, s: &[u8]) -> Vec<u8> { self.sign_with_hash(s, HashType::SHA256) }
|
pub fn sign(&self, s: &[u8]) -> Vec<u8> {
|
||||||
|
self.sign_with_hash(s, HashType::SHA256)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verifies a signature s (using OpenSSL's default scheme and sha256) on the SHA256 hash of a
|
* Verifies a signature s (using OpenSSL's default scheme and sha256) on the SHA256 hash of a
|
||||||
* message.
|
* message.
|
||||||
* Returns true if the signature is valid, and false otherwise.
|
* Returns true if the signature is valid, and false otherwise.
|
||||||
*/
|
*/
|
||||||
pub fn verify(&self, h: &[u8], s: &[u8]) -> bool { self.verify_with_hash(h, s, HashType::SHA256) }
|
pub fn verify(&self, h: &[u8], s: &[u8]) -> bool {
|
||||||
|
self.verify_with_hash(h, s, HashType::SHA256)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Signs data, using OpenSSL's default scheme and add ASN.1 information for the given hash type to the
|
* Signs data, using OpenSSL's default scheme and add ASN.1 information for the given hash type to the
|
||||||
|
|
@ -466,16 +498,15 @@ impl PKey {
|
||||||
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
let mut r = repeat(0u8).take(len as usize + 1).collect::<Vec<_>>();
|
||||||
|
|
||||||
let mut len = 0;
|
let mut len = 0;
|
||||||
let rv = ffi::RSA_sign(
|
let rv = ffi::RSA_sign(openssl_hash_nid(hash),
|
||||||
openssl_hash_nid(hash),
|
s.as_ptr(),
|
||||||
s.as_ptr(),
|
s.len() as c_uint,
|
||||||
s.len() as c_uint,
|
r.as_mut_ptr(),
|
||||||
r.as_mut_ptr(),
|
&mut len,
|
||||||
&mut len,
|
rsa);
|
||||||
rsa);
|
|
||||||
|
|
||||||
if rv < 0 as c_int {
|
if rv < 0 as c_int {
|
||||||
vec!()
|
vec![]
|
||||||
} else {
|
} else {
|
||||||
r.truncate(len as usize);
|
r.truncate(len as usize);
|
||||||
r
|
r
|
||||||
|
|
@ -490,21 +521,19 @@ impl PKey {
|
||||||
panic!("Could not get RSA key for verification");
|
panic!("Could not get RSA key for verification");
|
||||||
}
|
}
|
||||||
|
|
||||||
let rv = ffi::RSA_verify(
|
let rv = ffi::RSA_verify(openssl_hash_nid(hash),
|
||||||
openssl_hash_nid(hash),
|
h.as_ptr(),
|
||||||
h.as_ptr(),
|
h.len() as c_uint,
|
||||||
h.len() as c_uint,
|
s.as_ptr(),
|
||||||
s.as_ptr(),
|
s.len() as c_uint,
|
||||||
s.len() as c_uint,
|
rsa);
|
||||||
rsa
|
|
||||||
);
|
|
||||||
|
|
||||||
rv == 1 as c_int
|
rv == 1 as c_int
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub unsafe fn get_handle(&self) -> *mut ffi::EVP_PKEY {
|
pub unsafe fn get_handle(&self) -> *mut ffi::EVP_PKEY {
|
||||||
return self.evp
|
return self.evp;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn public_eq(&self, other: &PKey) -> bool {
|
pub fn public_eq(&self, other: &PKey) -> bool {
|
||||||
|
|
@ -568,8 +597,8 @@ mod tests {
|
||||||
fn test_private_key_from_pem() {
|
fn test_private_key_from_pem() {
|
||||||
let key_path = Path::new("test/key.pem");
|
let key_path = Path::new("test/key.pem");
|
||||||
let mut file = File::open(&key_path)
|
let mut file = File::open(&key_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/key.pem`");
|
.expect("Failed to open `test/key.pem`");
|
||||||
|
|
||||||
super::PKey::private_key_from_pem(&mut file).unwrap();
|
super::PKey::private_key_from_pem(&mut file).unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -578,8 +607,8 @@ mod tests {
|
||||||
fn test_public_key_from_pem() {
|
fn test_public_key_from_pem() {
|
||||||
let key_path = Path::new("test/key.pem.pub");
|
let key_path = Path::new("test/key.pem.pub");
|
||||||
let mut file = File::open(&key_path)
|
let mut file = File::open(&key_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/key.pem.pub`");
|
.expect("Failed to open `test/key.pem.pub`");
|
||||||
|
|
||||||
super::PKey::public_key_from_pem(&mut file).unwrap();
|
super::PKey::public_key_from_pem(&mut file).unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -588,7 +617,7 @@ mod tests {
|
||||||
fn test_private_encrypt() {
|
fn test_private_encrypt() {
|
||||||
let mut k0 = super::PKey::new();
|
let mut k0 = super::PKey::new();
|
||||||
let mut k1 = super::PKey::new();
|
let mut k1 = super::PKey::new();
|
||||||
let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8);
|
let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
|
||||||
k0.gen(512);
|
k0.gen(512);
|
||||||
k1.load_pub(&k0.save_pub());
|
k1.load_pub(&k0.save_pub());
|
||||||
let emsg = k0.private_encrypt(&msg);
|
let emsg = k0.private_encrypt(&msg);
|
||||||
|
|
@ -600,7 +629,7 @@ mod tests {
|
||||||
fn test_public_encrypt() {
|
fn test_public_encrypt() {
|
||||||
let mut k0 = super::PKey::new();
|
let mut k0 = super::PKey::new();
|
||||||
let mut k1 = super::PKey::new();
|
let mut k1 = super::PKey::new();
|
||||||
let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8);
|
let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
|
||||||
k0.gen(512);
|
k0.gen(512);
|
||||||
k1.load_pub(&k0.save_pub());
|
k1.load_pub(&k0.save_pub());
|
||||||
let emsg = k1.public_encrypt(&msg);
|
let emsg = k1.public_encrypt(&msg);
|
||||||
|
|
@ -612,7 +641,7 @@ mod tests {
|
||||||
fn test_public_encrypt_pkcs() {
|
fn test_public_encrypt_pkcs() {
|
||||||
let mut k0 = super::PKey::new();
|
let mut k0 = super::PKey::new();
|
||||||
let mut k1 = super::PKey::new();
|
let mut k1 = super::PKey::new();
|
||||||
let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8);
|
let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
|
||||||
k0.gen(512);
|
k0.gen(512);
|
||||||
k1.load_pub(&k0.save_pub());
|
k1.load_pub(&k0.save_pub());
|
||||||
let emsg = k1.public_encrypt_with_padding(&msg, super::EncryptionPadding::PKCS1v15);
|
let emsg = k1.public_encrypt_with_padding(&msg, super::EncryptionPadding::PKCS1v15);
|
||||||
|
|
@ -624,7 +653,7 @@ mod tests {
|
||||||
fn test_sign() {
|
fn test_sign() {
|
||||||
let mut k0 = super::PKey::new();
|
let mut k0 = super::PKey::new();
|
||||||
let mut k1 = super::PKey::new();
|
let mut k1 = super::PKey::new();
|
||||||
let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8);
|
let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
|
||||||
k0.gen(512);
|
k0.gen(512);
|
||||||
k1.load_pub(&k0.save_pub());
|
k1.load_pub(&k0.save_pub());
|
||||||
let sig = k0.sign(&msg);
|
let sig = k0.sign(&msg);
|
||||||
|
|
@ -636,7 +665,7 @@ mod tests {
|
||||||
fn test_sign_hashes() {
|
fn test_sign_hashes() {
|
||||||
let mut k0 = super::PKey::new();
|
let mut k0 = super::PKey::new();
|
||||||
let mut k1 = super::PKey::new();
|
let mut k1 = super::PKey::new();
|
||||||
let msg = vec!(0xdeu8, 0xadu8, 0xd0u8, 0x0du8);
|
let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
|
||||||
k0.gen(512);
|
k0.gen(512);
|
||||||
k1.load_pub(&k0.save_pub());
|
k1.load_pub(&k0.save_pub());
|
||||||
|
|
||||||
|
|
@ -674,8 +703,8 @@ mod tests {
|
||||||
fn test_pem() {
|
fn test_pem() {
|
||||||
let key_path = Path::new("test/key.pem");
|
let key_path = Path::new("test/key.pem");
|
||||||
let mut file = File::open(&key_path)
|
let mut file = File::open(&key_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/key.pem`");
|
.expect("Failed to open `test/key.pem`");
|
||||||
|
|
||||||
let key = super::PKey::private_key_from_pem(&mut file).unwrap();
|
let key = super::PKey::private_key_from_pem(&mut file).unwrap();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,9 @@ pub fn rand_bytes(len: usize) -> Vec<u8> {
|
||||||
|
|
||||||
ffi::init();
|
ffi::init();
|
||||||
let r = ffi::RAND_bytes(out.as_mut_ptr(), len as c_int);
|
let r = ffi::RAND_bytes(out.as_mut_ptr(), len as c_int);
|
||||||
if r != 1 as c_int { panic!() }
|
if r != 1 as c_int {
|
||||||
|
panic!()
|
||||||
|
}
|
||||||
|
|
||||||
out.set_len(len);
|
out.set_len(len);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
use std::iter::repeat;
|
use std::iter::repeat;
|
||||||
use libc::{c_int};
|
use libc::c_int;
|
||||||
|
|
||||||
use crypto::symm_internal::evpc;
|
use crypto::symm_internal::evpc;
|
||||||
use ffi;
|
use ffi;
|
||||||
|
|
@ -20,7 +20,7 @@ pub enum Type {
|
||||||
AES_128_XTS,
|
AES_128_XTS,
|
||||||
#[cfg(feature = "aes_ctr")]
|
#[cfg(feature = "aes_ctr")]
|
||||||
AES_128_CTR,
|
AES_128_CTR,
|
||||||
//AES_128_GCM,
|
// AES_128_GCM,
|
||||||
AES_128_CFB1,
|
AES_128_CFB1,
|
||||||
AES_128_CFB128,
|
AES_128_CFB128,
|
||||||
AES_128_CFB8,
|
AES_128_CFB8,
|
||||||
|
|
@ -32,7 +32,7 @@ pub enum Type {
|
||||||
AES_256_XTS,
|
AES_256_XTS,
|
||||||
#[cfg(feature = "aes_ctr")]
|
#[cfg(feature = "aes_ctr")]
|
||||||
AES_256_CTR,
|
AES_256_CTR,
|
||||||
//AES_256_GCM,
|
// AES_256_GCM,
|
||||||
AES_256_CFB1,
|
AES_256_CFB1,
|
||||||
AES_256_CFB128,
|
AES_256_CFB128,
|
||||||
AES_256_CFB8,
|
AES_256_CFB8,
|
||||||
|
|
@ -55,7 +55,12 @@ impl Crypter {
|
||||||
|
|
||||||
let ctx = unsafe { ffi::EVP_CIPHER_CTX_new() };
|
let ctx = unsafe { ffi::EVP_CIPHER_CTX_new() };
|
||||||
let (evp, keylen, blocksz) = evpc(t);
|
let (evp, keylen, blocksz) = evpc(t);
|
||||||
Crypter { evp: evp, ctx: ctx, keylen: keylen, blocksize: blocksz }
|
Crypter {
|
||||||
|
evp: evp,
|
||||||
|
ctx: ctx,
|
||||||
|
keylen: keylen,
|
||||||
|
blocksize: blocksz,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -65,7 +70,11 @@ impl Crypter {
|
||||||
pub fn pad(&self, padding: bool) {
|
pub fn pad(&self, padding: bool) {
|
||||||
if self.blocksize > 0 {
|
if self.blocksize > 0 {
|
||||||
unsafe {
|
unsafe {
|
||||||
let v = if padding { 1 as c_int } else { 0 };
|
let v = if padding {
|
||||||
|
1 as c_int
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
ffi::EVP_CIPHER_CTX_set_padding(self.ctx, v);
|
ffi::EVP_CIPHER_CTX_set_padding(self.ctx, v);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -82,13 +91,7 @@ impl Crypter {
|
||||||
};
|
};
|
||||||
assert_eq!(key.len(), self.keylen as usize);
|
assert_eq!(key.len(), self.keylen as usize);
|
||||||
|
|
||||||
ffi::EVP_CipherInit(
|
ffi::EVP_CipherInit(self.ctx, self.evp, key.as_ptr(), iv.as_ptr(), mode);
|
||||||
self.ctx,
|
|
||||||
self.evp,
|
|
||||||
key.as_ptr(),
|
|
||||||
iv.as_ptr(),
|
|
||||||
mode
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -102,13 +105,11 @@ impl Crypter {
|
||||||
let mut res = repeat(0u8).take(sum).collect::<Vec<_>>();
|
let mut res = repeat(0u8).take(sum).collect::<Vec<_>>();
|
||||||
let mut reslen = sum as c_int;
|
let mut reslen = sum as c_int;
|
||||||
|
|
||||||
ffi::EVP_CipherUpdate(
|
ffi::EVP_CipherUpdate(self.ctx,
|
||||||
self.ctx,
|
res.as_mut_ptr(),
|
||||||
res.as_mut_ptr(),
|
&mut reslen,
|
||||||
&mut reslen,
|
data.as_ptr(),
|
||||||
data.as_ptr(),
|
data.len() as c_int);
|
||||||
data.len() as c_int
|
|
||||||
);
|
|
||||||
|
|
||||||
res.truncate(reslen as usize);
|
res.truncate(reslen as usize);
|
||||||
res
|
res
|
||||||
|
|
@ -123,9 +124,7 @@ impl Crypter {
|
||||||
let mut res = repeat(0u8).take(self.blocksize as usize).collect::<Vec<_>>();
|
let mut res = repeat(0u8).take(self.blocksize as usize).collect::<Vec<_>>();
|
||||||
let mut reslen = self.blocksize as c_int;
|
let mut reslen = self.blocksize as c_int;
|
||||||
|
|
||||||
ffi::EVP_CipherFinal(self.ctx,
|
ffi::EVP_CipherFinal(self.ctx, res.as_mut_ptr(), &mut reslen);
|
||||||
res.as_mut_ptr(),
|
|
||||||
&mut reslen);
|
|
||||||
|
|
||||||
res.truncate(reslen as usize);
|
res.truncate(reslen as usize);
|
||||||
res
|
res
|
||||||
|
|
@ -175,17 +174,14 @@ mod tests {
|
||||||
// http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
|
// http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
|
||||||
#[test]
|
#[test]
|
||||||
fn test_aes_256_ecb() {
|
fn test_aes_256_ecb() {
|
||||||
let k0 =
|
let k0 = [0x00u8, 0x01u8, 0x02u8, 0x03u8, 0x04u8, 0x05u8, 0x06u8, 0x07u8, 0x08u8, 0x09u8,
|
||||||
[0x00u8, 0x01u8, 0x02u8, 0x03u8, 0x04u8, 0x05u8, 0x06u8, 0x07u8,
|
0x0au8, 0x0bu8, 0x0cu8, 0x0du8, 0x0eu8, 0x0fu8, 0x10u8, 0x11u8, 0x12u8, 0x13u8,
|
||||||
0x08u8, 0x09u8, 0x0au8, 0x0bu8, 0x0cu8, 0x0du8, 0x0eu8, 0x0fu8,
|
0x14u8, 0x15u8, 0x16u8, 0x17u8, 0x18u8, 0x19u8, 0x1au8, 0x1bu8, 0x1cu8, 0x1du8,
|
||||||
0x10u8, 0x11u8, 0x12u8, 0x13u8, 0x14u8, 0x15u8, 0x16u8, 0x17u8,
|
0x1eu8, 0x1fu8];
|
||||||
0x18u8, 0x19u8, 0x1au8, 0x1bu8, 0x1cu8, 0x1du8, 0x1eu8, 0x1fu8];
|
let p0 = [0x00u8, 0x11u8, 0x22u8, 0x33u8, 0x44u8, 0x55u8, 0x66u8, 0x77u8, 0x88u8, 0x99u8,
|
||||||
let p0 =
|
0xaau8, 0xbbu8, 0xccu8, 0xddu8, 0xeeu8, 0xffu8];
|
||||||
[0x00u8, 0x11u8, 0x22u8, 0x33u8, 0x44u8, 0x55u8, 0x66u8, 0x77u8,
|
let c0 = [0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8, 0xeau8, 0xfcu8,
|
||||||
0x88u8, 0x99u8, 0xaau8, 0xbbu8, 0xccu8, 0xddu8, 0xeeu8, 0xffu8];
|
0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8];
|
||||||
let c0 =
|
|
||||||
[0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8,
|
|
||||||
0xeau8, 0xfcu8, 0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8];
|
|
||||||
let c = super::Crypter::new(super::Type::AES_256_ECB);
|
let c = super::Crypter::new(super::Type::AES_256_ECB);
|
||||||
c.init(super::Mode::Encrypt, &k0, &[]);
|
c.init(super::Mode::Encrypt, &k0, &[]);
|
||||||
c.pad(false);
|
c.pad(false);
|
||||||
|
|
@ -202,22 +198,16 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_aes_256_cbc_decrypt() {
|
fn test_aes_256_cbc_decrypt() {
|
||||||
let cr = super::Crypter::new(super::Type::AES_256_CBC);
|
let cr = super::Crypter::new(super::Type::AES_256_CBC);
|
||||||
let iv = [
|
let iv = [4_u8, 223_u8, 153_u8, 219_u8, 28_u8, 142_u8, 234_u8, 68_u8, 227_u8, 69_u8,
|
||||||
4_u8, 223_u8, 153_u8, 219_u8, 28_u8, 142_u8, 234_u8, 68_u8, 227_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,
|
||||||
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, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8, 0_u8,
|
let data = [143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8, 241_u8, 242_u8, 31_u8,
|
||||||
0_u8, 0_u8, 0_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,
|
||||||
let data = [
|
65_u8, 207_u8];
|
||||||
143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8,
|
let ciphered_data = [0x4a_u8, 0x2e_u8, 0xe5_u8, 0x6_u8, 0xbf_u8, 0xcf_u8, 0xf2_u8,
|
||||||
241_u8, 242_u8, 31_u8, 154_u8, 56_u8, 198_u8, 145_u8, 192_u8, 64_u8,
|
0xd7_u8, 0xea_u8, 0x2d_u8, 0xb1_u8, 0x85_u8, 0x6c_u8, 0x93_u8,
|
||||||
2_u8, 245_u8, 167_u8, 220_u8, 55_u8, 119_u8, 233_u8, 136_u8, 139_u8,
|
0x65_u8, 0x6f_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
|
|
||||||
];
|
|
||||||
cr.init(super::Mode::Decrypt, &data, &iv);
|
cr.init(super::Mode::Decrypt, &data, &iv);
|
||||||
cr.pad(false);
|
cr.pad(false);
|
||||||
let unciphered_data_1 = cr.update(&ciphered_data);
|
let unciphered_data_1 = cr.update(&ciphered_data);
|
||||||
|
|
@ -234,7 +224,9 @@ mod tests {
|
||||||
use serialize::hex::ToHex;
|
use serialize::hex::ToHex;
|
||||||
|
|
||||||
let cipher = super::Crypter::new(ciphertype);
|
let cipher = super::Crypter::new(ciphertype);
|
||||||
cipher.init(super::Mode::Encrypt, &key.from_hex().unwrap(), &iv.from_hex().unwrap());
|
cipher.init(super::Mode::Encrypt,
|
||||||
|
&key.from_hex().unwrap(),
|
||||||
|
&iv.from_hex().unwrap());
|
||||||
|
|
||||||
let expected = ct.from_hex().unwrap();
|
let expected = ct.from_hex().unwrap();
|
||||||
let mut computed = cipher.update(&pt.from_hex().unwrap());
|
let mut computed = cipher.update(&pt.from_hex().unwrap());
|
||||||
|
|
@ -245,7 +237,8 @@ mod tests {
|
||||||
println!("Expected: {}", expected.to_hex());
|
println!("Expected: {}", expected.to_hex());
|
||||||
if computed.len() != expected.len() {
|
if computed.len() != expected.len() {
|
||||||
println!("Lengths differ: {} in computed vs {} expected",
|
println!("Lengths differ: {} in computed vs {} expected",
|
||||||
computed.len(), expected.len());
|
computed.len(),
|
||||||
|
expected.len());
|
||||||
}
|
}
|
||||||
panic!("test failure");
|
panic!("test failure");
|
||||||
}
|
}
|
||||||
|
|
@ -267,9 +260,12 @@ mod tests {
|
||||||
fn test_aes256_xts() {
|
fn test_aes256_xts() {
|
||||||
// Test case 174 from
|
// Test case 174 from
|
||||||
// http://csrc.nist.gov/groups/STM/cavp/documents/aes/XTSTestVectors.zip
|
// http://csrc.nist.gov/groups/STM/cavp/documents/aes/XTSTestVectors.zip
|
||||||
let pt = "77f4ef63d734ebd028508da66c22cdebdd52ecd6ee2ab0a50bc8ad0cfd692ca5fcd4e6dedc45df7f6503f462611dc542";
|
let pt = "77f4ef63d734ebd028508da66c22cdebdd52ecd6ee2ab0a50bc8ad0cfd692ca5fcd4e6dedc45df7f\
|
||||||
let ct = "ce7d905a7776ac72f240d22aafed5e4eb7566cdc7211220e970da634ce015f131a5ecb8d400bc9e84f0b81d8725dbbc7";
|
6503f462611dc542";
|
||||||
let key = "b6bfef891f83b5ff073f2231267be51eb084b791fa19a154399c0684c8b2dfcb37de77d28bbda3b4180026ad640b74243b3133e7b9fae629403f6733423dae28";
|
let ct = "ce7d905a7776ac72f240d22aafed5e4eb7566cdc7211220e970da634ce015f131a5ecb8d400bc9e8\
|
||||||
|
4f0b81d8725dbbc7";
|
||||||
|
let key = "b6bfef891f83b5ff073f2231267be51eb084b791fa19a154399c0684c8b2dfcb37de77d28bbda3b\
|
||||||
|
4180026ad640b74243b3133e7b9fae629403f6733423dae28";
|
||||||
let iv = "db200efb7eaaa737dbdf40babb68953f";
|
let iv = "db200efb7eaaa737dbdf40babb68953f";
|
||||||
|
|
||||||
cipher_test(super::Type::AES_256_XTS, pt, ct, key, iv);
|
cipher_test(super::Type::AES_256_XTS, pt, ct, key, iv);
|
||||||
|
|
@ -279,24 +275,26 @@ mod tests {
|
||||||
#[cfg(feature = "aes_ctr")]
|
#[cfg(feature = "aes_ctr")]
|
||||||
fn test_aes128_ctr() {
|
fn test_aes128_ctr() {
|
||||||
|
|
||||||
let pt = "6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710";
|
let pt = "6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411\
|
||||||
let ct = "874D6191B620E3261BEF6864990DB6CE9806F66B7970FDFF8617187BB9FFFDFF5AE4DF3EDBD5D35E5B4F09020DB03EAB1E031DDA2FBE03D1792170A0F3009CEE";
|
E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710";
|
||||||
|
let ct = "874D6191B620E3261BEF6864990DB6CE9806F66B7970FDFF8617187BB9FFFDFF5AE4DF3EDBD5D35E\
|
||||||
|
5B4F09020DB03EAB1E031DDA2FBE03D1792170A0F3009CEE";
|
||||||
let key = "2B7E151628AED2A6ABF7158809CF4F3C";
|
let key = "2B7E151628AED2A6ABF7158809CF4F3C";
|
||||||
let iv = "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
|
let iv = "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
|
||||||
|
|
||||||
cipher_test(super::Type::AES_128_CTR, pt, ct, key, iv);
|
cipher_test(super::Type::AES_128_CTR, pt, ct, key, iv);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*#[test]
|
// #[test]
|
||||||
fn test_aes128_gcm() {
|
// fn test_aes128_gcm() {
|
||||||
// Test case 3 in GCM spec
|
// Test case 3 in GCM spec
|
||||||
let pt = ~"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255";
|
// let pt = ~"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255";
|
||||||
let ct = ~"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f59854d5c2af327cd64a62cf35abd2ba6fab4";
|
// let ct = ~"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f59854d5c2af327cd64a62cf35abd2ba6fab4";
|
||||||
let key = ~"feffe9928665731c6d6a8f9467308308";
|
// let key = ~"feffe9928665731c6d6a8f9467308308";
|
||||||
let iv = ~"cafebabefacedbaddecaf888";
|
// let iv = ~"cafebabefacedbaddecaf888";
|
||||||
|
//
|
||||||
cipher_test(super::AES_128_GCM, pt, ct, key, iv);
|
// cipher_test(super::AES_128_GCM, pt, ct, key, iv);
|
||||||
}*/
|
// }
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_aes128_cfb1() {
|
fn test_aes128_cfb1() {
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ pub fn evpc(t: symm::Type) -> (*const ffi::EVP_CIPHER, u32, u32) {
|
||||||
symm::Type::AES_128_XTS => (ffi::EVP_aes_128_xts(), 32, 16),
|
symm::Type::AES_128_XTS => (ffi::EVP_aes_128_xts(), 32, 16),
|
||||||
#[cfg(feature = "aes_ctr")]
|
#[cfg(feature = "aes_ctr")]
|
||||||
symm::Type::AES_128_CTR => (ffi::EVP_aes_128_ctr(), 16, 0),
|
symm::Type::AES_128_CTR => (ffi::EVP_aes_128_ctr(), 16, 0),
|
||||||
//AES_128_GCM => (EVP_aes_128_gcm(), 16, 16),
|
// AES_128_GCM => (EVP_aes_128_gcm(), 16, 16),
|
||||||
symm::Type::AES_128_CFB1 => (ffi::EVP_aes_128_cfb1(), 16, 16),
|
symm::Type::AES_128_CFB1 => (ffi::EVP_aes_128_cfb1(), 16, 16),
|
||||||
symm::Type::AES_128_CFB128 => (ffi::EVP_aes_128_cfb128(), 16, 16),
|
symm::Type::AES_128_CFB128 => (ffi::EVP_aes_128_cfb128(), 16, 16),
|
||||||
symm::Type::AES_128_CFB8 => (ffi::EVP_aes_128_cfb8(), 16, 16),
|
symm::Type::AES_128_CFB8 => (ffi::EVP_aes_128_cfb8(), 16, 16),
|
||||||
|
|
@ -21,7 +21,7 @@ pub fn evpc(t: symm::Type) -> (*const ffi::EVP_CIPHER, u32, u32) {
|
||||||
symm::Type::AES_256_XTS => (ffi::EVP_aes_256_xts(), 64, 16),
|
symm::Type::AES_256_XTS => (ffi::EVP_aes_256_xts(), 64, 16),
|
||||||
#[cfg(feature = "aes_ctr")]
|
#[cfg(feature = "aes_ctr")]
|
||||||
symm::Type::AES_256_CTR => (ffi::EVP_aes_256_ctr(), 32, 0),
|
symm::Type::AES_256_CTR => (ffi::EVP_aes_256_ctr(), 32, 0),
|
||||||
//AES_256_GCM => (EVP_aes_256_gcm(), 32, 16),
|
// AES_256_GCM => (EVP_aes_256_gcm(), 32, 16),
|
||||||
symm::Type::AES_256_CFB1 => (ffi::EVP_aes_256_cfb1(), 32, 16),
|
symm::Type::AES_256_CFB1 => (ffi::EVP_aes_256_cfb1(), 32, 16),
|
||||||
symm::Type::AES_256_CFB128 => (ffi::EVP_aes_256_cfb128(), 32, 16),
|
symm::Type::AES_256_CFB128 => (ffi::EVP_aes_256_cfb128(), 32, 16),
|
||||||
symm::Type::AES_256_CFB8 => (ffi::EVP_aes_256_cfb8(), 32, 16),
|
symm::Type::AES_256_CFB8 => (ffi::EVP_aes_256_cfb8(), 32, 16),
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,9 @@ impl DH {
|
||||||
Ok(DH(dh))
|
Ok(DH(dh))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_pem<R>(reader: &mut R) -> Result<DH, SslError> where R: Read {
|
pub fn from_pem<R>(reader: &mut R) -> Result<DH, SslError>
|
||||||
|
where R: Read
|
||||||
|
{
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
||||||
let dh = unsafe {
|
let dh = unsafe {
|
||||||
|
|
@ -91,9 +93,29 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_dh() {
|
fn test_dh() {
|
||||||
let ctx = SslContext::new(Sslv23).unwrap();
|
let ctx = SslContext::new(Sslv23).unwrap();
|
||||||
let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597").unwrap();
|
let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435\
|
||||||
let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659").unwrap();
|
E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF429\
|
||||||
let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3").unwrap();
|
6D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C02\
|
||||||
|
2E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF1230\
|
||||||
|
7F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9\
|
||||||
|
A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251C\
|
||||||
|
CACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE\
|
||||||
|
621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D227\
|
||||||
|
6E11715F693877FAD7EF09CADB094AE91E1A1597")
|
||||||
|
.unwrap();
|
||||||
|
let g = BigNum::from_hex_str("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0\
|
||||||
|
BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773\
|
||||||
|
BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2D\
|
||||||
|
DF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428E\
|
||||||
|
BC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BF\
|
||||||
|
FE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7\
|
||||||
|
D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92\
|
||||||
|
B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148\
|
||||||
|
D47954515E2327CFEF98C582664B4C0F6CC41659")
|
||||||
|
.unwrap();
|
||||||
|
let q = BigNum::from_hex_str("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F\
|
||||||
|
5FBD3")
|
||||||
|
.unwrap();
|
||||||
let dh = DH::from_params(p, g, q).unwrap();
|
let dh = DH::from_params(p, g, q).unwrap();
|
||||||
ctx.set_tmp_dh(dh).unwrap();
|
ctx.set_tmp_dh(dh).unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -103,8 +125,8 @@ mod tests {
|
||||||
let ctx = SslContext::new(Sslv23).unwrap();
|
let ctx = SslContext::new(Sslv23).unwrap();
|
||||||
let pem_path = Path::new("test/dhparams.pem");
|
let pem_path = Path::new("test/dhparams.pem");
|
||||||
let mut file = File::open(&pem_path)
|
let mut file = File::open(&pem_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/dhparams.pem`");
|
.expect("Failed to open `test/dhparams.pem`");
|
||||||
let dh = DH::from_pem(&mut file).ok().expect("Failed to load PEM");
|
let dh = DH::from_pem(&mut file).ok().expect("Failed to load PEM");
|
||||||
ctx.set_tmp_dh(dh).unwrap();
|
ctx.set_tmp_dh(dh).unwrap();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.2")]
|
#![doc(html_root_url="https://sfackler.github.io/rust-openssl/doc/v0.7.3")]
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate bitflags;
|
extern crate bitflags;
|
||||||
|
|
|
||||||
|
|
@ -120,8 +120,8 @@ pub enum Nid {
|
||||||
RSA_SHA1_2,
|
RSA_SHA1_2,
|
||||||
DSA,
|
DSA,
|
||||||
RIPEMD160,
|
RIPEMD160,
|
||||||
/* 118 missing */
|
// 118 missing
|
||||||
RSA_RIPEMD160=119,
|
RSA_RIPEMD160 = 119,
|
||||||
RC5_CBC,
|
RC5_CBC,
|
||||||
RC5_ECB,
|
RC5_ECB,
|
||||||
RC5_CFB,
|
RC5_CFB,
|
||||||
|
|
@ -169,5 +169,5 @@ pub enum Nid {
|
||||||
ID_QT_CPS,
|
ID_QT_CPS,
|
||||||
ID_QT_UNOTICE,
|
ID_QT_UNOTICE,
|
||||||
RC2_64_CBC,
|
RC2_64_CBC,
|
||||||
SMIMECaps
|
SMIMECaps,
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -95,7 +95,7 @@ unsafe extern "C" fn bwrite<S: Write>(bio: *mut BIO, buf: *const c_char, len: c_
|
||||||
match state.stream.write(buf) {
|
match state.stream.write(buf) {
|
||||||
Ok(len) => len as c_int,
|
Ok(len) => len as c_int,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if err.kind() == io::ErrorKind::WouldBlock {
|
if retriable_error(&err) {
|
||||||
BIO_set_retry_write(bio);
|
BIO_set_retry_write(bio);
|
||||||
}
|
}
|
||||||
state.error = Some(err);
|
state.error = Some(err);
|
||||||
|
|
@ -112,7 +112,7 @@ unsafe extern "C" fn bread<S: Read>(bio: *mut BIO, buf: *mut c_char, len: c_int)
|
||||||
match state.stream.read(buf) {
|
match state.stream.read(buf) {
|
||||||
Ok(len) => len as c_int,
|
Ok(len) => len as c_int,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if err.kind() == io::ErrorKind::WouldBlock {
|
if retriable_error(&err) {
|
||||||
BIO_set_retry_read(bio);
|
BIO_set_retry_read(bio);
|
||||||
}
|
}
|
||||||
state.error = Some(err);
|
state.error = Some(err);
|
||||||
|
|
@ -121,6 +121,13 @@ unsafe extern "C" fn bread<S: Read>(bio: *mut BIO, buf: *mut c_char, len: c_int)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn retriable_error(err: &io::Error) -> bool {
|
||||||
|
match err.kind() {
|
||||||
|
io::ErrorKind::WouldBlock | io::ErrorKind::NotConnected => true,
|
||||||
|
_ => false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
unsafe extern "C" fn bputs<S: Write>(bio: *mut BIO, s: *const c_char) -> c_int {
|
unsafe extern "C" fn bputs<S: Write>(bio: *mut BIO, s: *const c_char) -> c_int {
|
||||||
bwrite::<S>(bio, s, strlen(s) as c_int)
|
bwrite::<S>(bio, s, strlen(s) as c_int)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -50,7 +50,7 @@ impl fmt::Display for Error {
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
_ => Ok(())
|
_ => Ok(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -72,7 +72,7 @@ impl error::Error for Error {
|
||||||
Error::WantRead(ref err) => Some(err),
|
Error::WantRead(ref err) => Some(err),
|
||||||
Error::WantWrite(ref err) => Some(err),
|
Error::WantWrite(ref err) => Some(err),
|
||||||
Error::Stream(ref err) => Some(err),
|
Error::Stream(ref err) => Some(err),
|
||||||
_ => None
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -85,11 +85,11 @@ impl OpenSslError {
|
||||||
pub fn get_stack() -> Vec<OpenSslError> {
|
pub fn get_stack() -> Vec<OpenSslError> {
|
||||||
ffi::init();
|
ffi::init();
|
||||||
|
|
||||||
let mut errs = vec!();
|
let mut errs = vec![];
|
||||||
loop {
|
loop {
|
||||||
match unsafe { ffi::ERR_get_error() } {
|
match unsafe { ffi::ERR_get_error() } {
|
||||||
0 => break,
|
0 => break,
|
||||||
err => errs.push(OpenSslError(err))
|
err => errs.push(OpenSslError(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
errs
|
errs
|
||||||
|
|
@ -196,7 +196,7 @@ impl error::Error for SslError {
|
||||||
fn cause(&self) -> Option<&error::Error> {
|
fn cause(&self) -> Option<&error::Error> {
|
||||||
match *self {
|
match *self {
|
||||||
StreamError(ref err) => Some(err as &error::Error),
|
StreamError(ref err) => Some(err as &error::Error),
|
||||||
_ => None
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -211,15 +211,19 @@ impl error::Error for NonblockingSslError {
|
||||||
fn description(&self) -> &str {
|
fn description(&self) -> &str {
|
||||||
match *self {
|
match *self {
|
||||||
NonblockingSslError::SslError(ref e) => e.description(),
|
NonblockingSslError::SslError(ref e) => e.description(),
|
||||||
NonblockingSslError::WantRead => "The OpenSSL library wants data from the remote socket",
|
NonblockingSslError::WantRead => {
|
||||||
NonblockingSslError::WantWrite => "The OpenSSL library want to send data to the remote socket",
|
"The OpenSSL library wants data from the remote socket"
|
||||||
|
}
|
||||||
|
NonblockingSslError::WantWrite => {
|
||||||
|
"The OpenSSL library want to send data to the remote socket"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cause(&self) -> Option<&error::Error> {
|
fn cause(&self) -> Option<&error::Error> {
|
||||||
match *self {
|
match *self {
|
||||||
NonblockingSslError::SslError(ref e) => e.cause(),
|
NonblockingSslError::SslError(ref e) => e.cause(),
|
||||||
_ => None
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -240,8 +244,8 @@ pub enum OpensslError {
|
||||||
/// The function reporting the error
|
/// The function reporting the error
|
||||||
function: String,
|
function: String,
|
||||||
/// The reason for the error
|
/// The reason for the error
|
||||||
reason: String
|
reason: String,
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl OpensslError {
|
impl OpensslError {
|
||||||
|
|
@ -250,7 +254,7 @@ impl OpensslError {
|
||||||
UnknownError {
|
UnknownError {
|
||||||
library: get_lib(err).to_owned(),
|
library: get_lib(err).to_owned(),
|
||||||
function: get_func(err).to_owned(),
|
function: get_func(err).to_owned(),
|
||||||
reason: get_reason(err).to_owned()
|
reason: get_reason(err).to_owned(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -283,11 +287,11 @@ impl SslError {
|
||||||
/// Creates a new `OpenSslErrors` with the current contents of the error
|
/// Creates a new `OpenSslErrors` with the current contents of the error
|
||||||
/// stack.
|
/// stack.
|
||||||
pub fn get() -> SslError {
|
pub fn get() -> SslError {
|
||||||
let mut errs = vec!();
|
let mut errs = vec![];
|
||||||
loop {
|
loop {
|
||||||
match unsafe { ffi::ERR_get_error() } {
|
match unsafe { ffi::ERR_get_error() } {
|
||||||
0 => break,
|
0 => break,
|
||||||
err => errs.push(OpensslError::from_error_code(err))
|
err => errs.push(OpensslError::from_error_code(err)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
OpenSslErrors(errs)
|
OpenSslErrors(errs)
|
||||||
|
|
@ -303,7 +307,7 @@ impl SslError {
|
||||||
fn test_uknown_error_should_have_correct_messages() {
|
fn test_uknown_error_should_have_correct_messages() {
|
||||||
let errs = match SslError::from_error(336032784) {
|
let errs = match SslError::from_error(336032784) {
|
||||||
OpenSslErrors(errs) => errs,
|
OpenSslErrors(errs) => errs,
|
||||||
_ => panic!("This should always be an `OpenSslErrors` variant.")
|
_ => panic!("This should always be an `OpenSslErrors` variant."),
|
||||||
};
|
};
|
||||||
|
|
||||||
let UnknownError { ref library, ref function, ref reason } = errs[0];
|
let UnknownError { ref library, ref function, ref reason } = errs[0];
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,7 @@ extern "C" {
|
||||||
}
|
}
|
||||||
|
|
||||||
static mut VERIFY_IDX: c_int = -1;
|
static mut VERIFY_IDX: c_int = -1;
|
||||||
static mut SNI_IDX: c_int = -1;
|
static mut SNI_IDX: c_int = -1;
|
||||||
|
|
||||||
/// Manually initialize SSL.
|
/// Manually initialize SSL.
|
||||||
/// It is optional to call this function and safe to do so more than once.
|
/// It is optional to call this function and safe to do so more than once.
|
||||||
|
|
@ -56,13 +56,11 @@ pub fn init() {
|
||||||
INIT.call_once(|| {
|
INIT.call_once(|| {
|
||||||
ffi::init();
|
ffi::init();
|
||||||
|
|
||||||
let verify_idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None,
|
let verify_idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None, None, None);
|
||||||
None, None);
|
|
||||||
assert!(verify_idx >= 0);
|
assert!(verify_idx >= 0);
|
||||||
VERIFY_IDX = verify_idx;
|
VERIFY_IDX = verify_idx;
|
||||||
|
|
||||||
let sni_idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None,
|
let sni_idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None, None, None);
|
||||||
None, None);
|
|
||||||
assert!(sni_idx >= 0);
|
assert!(sni_idx >= 0);
|
||||||
SNI_IDX = sni_idx;
|
SNI_IDX = sni_idx;
|
||||||
});
|
});
|
||||||
|
|
@ -234,9 +232,7 @@ lazy_static! {
|
||||||
// Registers a destructor for the data which will be called
|
// Registers a destructor for the data which will be called
|
||||||
// when context is freed
|
// when context is freed
|
||||||
fn get_verify_data_idx<T: Any + 'static>() -> c_int {
|
fn get_verify_data_idx<T: Any + 'static>() -> c_int {
|
||||||
*INDEXES.lock().unwrap().entry(TypeId::of::<T>()).or_insert_with(|| {
|
*INDEXES.lock().unwrap().entry(TypeId::of::<T>()).or_insert_with(|| get_new_idx::<T>())
|
||||||
get_new_idx::<T>()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "npn")]
|
#[cfg(feature = "npn")]
|
||||||
|
|
@ -251,9 +247,12 @@ lazy_static! {
|
||||||
/// Determine a new index to use for SSL CTX ex data.
|
/// Determine a new index to use for SSL CTX ex data.
|
||||||
/// Registers a destruct for the data which will be called by openssl when the context is freed.
|
/// Registers a destruct for the data which will be called by openssl when the context is freed.
|
||||||
fn get_new_idx<T>() -> c_int {
|
fn get_new_idx<T>() -> c_int {
|
||||||
extern fn free_data_box<T>(_parent: *mut c_void, ptr: *mut c_void,
|
extern "C" fn free_data_box<T>(_parent: *mut c_void,
|
||||||
_ad: *mut ffi::CRYPTO_EX_DATA, _idx: c_int,
|
ptr: *mut c_void,
|
||||||
_argl: c_long, _argp: *mut c_void) {
|
_ad: *mut ffi::CRYPTO_EX_DATA,
|
||||||
|
_idx: c_int,
|
||||||
|
_argl: c_long,
|
||||||
|
_argp: *mut c_void) {
|
||||||
if !ptr.is_null() {
|
if !ptr.is_null() {
|
||||||
let _: Box<T> = unsafe { mem::transmute(ptr) };
|
let _: Box<T> = unsafe { mem::transmute(ptr) };
|
||||||
}
|
}
|
||||||
|
|
@ -261,15 +260,13 @@ fn get_new_idx<T>() -> c_int {
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let f: ffi::CRYPTO_EX_free = free_data_box::<T>;
|
let f: ffi::CRYPTO_EX_free = free_data_box::<T>;
|
||||||
let idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None,
|
let idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None, None, Some(f));
|
||||||
None, Some(f));
|
|
||||||
assert!(idx >= 0);
|
assert!(idx >= 0);
|
||||||
idx
|
idx
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX)
|
extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int {
|
||||||
-> c_int {
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx();
|
let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx();
|
||||||
let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx);
|
let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx);
|
||||||
|
|
@ -281,14 +278,16 @@ extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX)
|
||||||
|
|
||||||
match verify {
|
match verify {
|
||||||
None => preverify_ok,
|
None => preverify_ok,
|
||||||
Some(verify) => verify(preverify_ok != 0, &ctx) as c_int
|
Some(verify) => verify(preverify_ok != 0, &ctx) as c_int,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extern fn raw_verify_with_data<T>(preverify_ok: c_int,
|
extern "C" fn raw_verify_with_data<T>(preverify_ok: c_int,
|
||||||
x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int
|
x509_ctx: *mut ffi::X509_STORE_CTX)
|
||||||
where T: Any + 'static {
|
-> c_int
|
||||||
|
where T: Any + 'static
|
||||||
|
{
|
||||||
unsafe {
|
unsafe {
|
||||||
let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx();
|
let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx();
|
||||||
let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx);
|
let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx);
|
||||||
|
|
@ -304,15 +303,14 @@ extern fn raw_verify_with_data<T>(preverify_ok: c_int,
|
||||||
|
|
||||||
let res = match verify {
|
let res = match verify {
|
||||||
None => preverify_ok,
|
None => preverify_ok,
|
||||||
Some(verify) => verify(preverify_ok != 0, &ctx, data) as c_int
|
Some(verify) => verify(preverify_ok != 0, &ctx, data) as c_int,
|
||||||
};
|
};
|
||||||
|
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, _arg: *mut c_void)
|
extern "C" fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, _arg: *mut c_void) -> c_int {
|
||||||
-> c_int {
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
|
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
|
||||||
let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, SNI_IDX);
|
let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, SNI_IDX);
|
||||||
|
|
@ -322,15 +320,16 @@ extern fn raw_sni(ssl: *mut ffi::SSL, ad: &mut c_int, _arg: *mut c_void)
|
||||||
|
|
||||||
let res = match callback {
|
let res = match callback {
|
||||||
None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL,
|
None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL,
|
||||||
Some(callback) => callback(&mut s, ad)
|
Some(callback) => callback(&mut s, ad),
|
||||||
};
|
};
|
||||||
|
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extern fn raw_sni_with_data<T>(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_void) -> c_int
|
extern "C" fn raw_sni_with_data<T>(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_void) -> c_int
|
||||||
where T: Any + 'static {
|
where T: Any + 'static
|
||||||
|
{
|
||||||
unsafe {
|
unsafe {
|
||||||
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
|
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
|
||||||
|
|
||||||
|
|
@ -343,7 +342,7 @@ extern fn raw_sni_with_data<T>(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_v
|
||||||
|
|
||||||
let res = match callback {
|
let res = match callback {
|
||||||
None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL,
|
None => ffi::SSL_TLSEXT_ERR_ALERT_FATAL,
|
||||||
Some(callback) => callback(&mut s, ad, &*data)
|
Some(callback) => callback(&mut s, ad, &*data),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Since data might be required on the next verification
|
// Since data might be required on the next verification
|
||||||
|
|
@ -357,25 +356,29 @@ extern fn raw_sni_with_data<T>(ssl: *mut ffi::SSL, ad: &mut c_int, arg: *mut c_v
|
||||||
|
|
||||||
#[cfg(any(feature = "npn", feature = "alpn"))]
|
#[cfg(any(feature = "npn", feature = "alpn"))]
|
||||||
unsafe fn select_proto_using(ssl: *mut ffi::SSL,
|
unsafe fn select_proto_using(ssl: *mut ffi::SSL,
|
||||||
out: *mut *mut c_uchar, outlen: *mut c_uchar,
|
out: *mut *mut c_uchar,
|
||||||
inbuf: *const c_uchar, inlen: c_uint,
|
outlen: *mut c_uchar,
|
||||||
ex_data: c_int) -> c_int {
|
inbuf: *const c_uchar,
|
||||||
|
inlen: c_uint,
|
||||||
|
ex_data: c_int)
|
||||||
|
-> c_int {
|
||||||
|
|
||||||
// First, get the list of protocols (that the client should support) saved in the context
|
// First, get the list of protocols (that the client should support) saved in the context
|
||||||
// extra data.
|
// extra data.
|
||||||
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
|
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
|
||||||
let protocols = ffi::SSL_CTX_get_ex_data(ssl_ctx, ex_data);
|
let protocols = ffi::SSL_CTX_get_ex_data(ssl_ctx, ex_data);
|
||||||
let protocols: &Vec<u8> = mem::transmute(protocols);
|
let protocols: &Vec<u8> = mem::transmute(protocols);
|
||||||
// Prepare the client list parameters to be passed to the OpenSSL function...
|
// Prepare the client list parameters to be passed to the OpenSSL function...
|
||||||
let client = protocols.as_ptr();
|
let client = protocols.as_ptr();
|
||||||
let client_len = protocols.len() as c_uint;
|
let client_len = protocols.len() as c_uint;
|
||||||
// Finally, let OpenSSL find a protocol to be used, by matching the given server and
|
// Finally, let OpenSSL find a protocol to be used, by matching the given server and
|
||||||
// client lists.
|
// client lists.
|
||||||
if ffi::SSL_select_next_proto(out, outlen, inbuf, inlen, client, client_len) != ffi::OPENSSL_NPN_NEGOTIATED {
|
if ffi::SSL_select_next_proto(out, outlen, inbuf, inlen, client, client_len) !=
|
||||||
ffi::SSL_TLSEXT_ERR_NOACK
|
ffi::OPENSSL_NPN_NEGOTIATED {
|
||||||
} else {
|
ffi::SSL_TLSEXT_ERR_NOACK
|
||||||
ffi::SSL_TLSEXT_ERR_OK
|
} else {
|
||||||
}
|
ffi::SSL_TLSEXT_ERR_OK
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The function is given as the callback to `SSL_CTX_set_next_proto_select_cb`.
|
/// The function is given as the callback to `SSL_CTX_set_next_proto_select_cb`.
|
||||||
|
|
@ -385,23 +388,25 @@ unsafe fn select_proto_using(ssl: *mut ffi::SSL,
|
||||||
/// function. The list of protocols supported by the client is found in the extra data of the
|
/// function. The list of protocols supported by the client is found in the extra data of the
|
||||||
/// OpenSSL context.
|
/// OpenSSL context.
|
||||||
#[cfg(feature = "npn")]
|
#[cfg(feature = "npn")]
|
||||||
extern fn raw_next_proto_select_cb(ssl: *mut ffi::SSL,
|
extern "C" fn raw_next_proto_select_cb(ssl: *mut ffi::SSL,
|
||||||
out: *mut *mut c_uchar, outlen: *mut c_uchar,
|
out: *mut *mut c_uchar,
|
||||||
inbuf: *const c_uchar, inlen: c_uint,
|
outlen: *mut c_uchar,
|
||||||
_arg: *mut c_void) -> c_int {
|
inbuf: *const c_uchar,
|
||||||
unsafe {
|
inlen: c_uint,
|
||||||
select_proto_using(ssl, out, outlen, inbuf, inlen, *NPN_PROTOS_IDX)
|
_arg: *mut c_void)
|
||||||
}
|
-> c_int {
|
||||||
|
unsafe { select_proto_using(ssl, out, outlen, inbuf, inlen, *NPN_PROTOS_IDX) }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "alpn")]
|
#[cfg(feature = "alpn")]
|
||||||
extern fn raw_alpn_select_cb(ssl: *mut ffi::SSL,
|
extern "C" fn raw_alpn_select_cb(ssl: *mut ffi::SSL,
|
||||||
out: *mut *mut c_uchar, outlen: *mut c_uchar,
|
out: *mut *mut c_uchar,
|
||||||
inbuf: *const c_uchar, inlen: c_uint,
|
outlen: *mut c_uchar,
|
||||||
_arg: *mut c_void) -> c_int {
|
inbuf: *const c_uchar,
|
||||||
unsafe {
|
inlen: c_uint,
|
||||||
select_proto_using(ssl, out, outlen, inbuf, inlen, *ALPN_PROTOS_IDX)
|
_arg: *mut c_void)
|
||||||
}
|
-> c_int {
|
||||||
|
unsafe { select_proto_using(ssl, out, outlen, inbuf, inlen, *ALPN_PROTOS_IDX) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The function is given as the callback to `SSL_CTX_set_next_protos_advertised_cb`.
|
/// The function is given as the callback to `SSL_CTX_set_next_protos_advertised_cb`.
|
||||||
|
|
@ -412,9 +417,11 @@ extern fn raw_alpn_select_cb(ssl: *mut ffi::SSL,
|
||||||
/// The list of supported protocols is found in the extra data of the OpenSSL
|
/// The list of supported protocols is found in the extra data of the OpenSSL
|
||||||
/// context.
|
/// context.
|
||||||
#[cfg(feature = "npn")]
|
#[cfg(feature = "npn")]
|
||||||
extern fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL,
|
extern "C" fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL,
|
||||||
out: *mut *const c_uchar, outlen: *mut c_uint,
|
out: *mut *const c_uchar,
|
||||||
_arg: *mut c_void) -> c_int {
|
outlen: *mut c_uint,
|
||||||
|
_arg: *mut c_void)
|
||||||
|
-> c_int {
|
||||||
unsafe {
|
unsafe {
|
||||||
// First, get the list of (supported) protocols saved in the context extra data.
|
// First, get the list of (supported) protocols saved in the context extra data.
|
||||||
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
|
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
|
||||||
|
|
@ -437,8 +444,7 @@ extern fn raw_next_protos_advertise_cb(ssl: *mut ffi::SSL,
|
||||||
/// Convert a set of byte slices into a series of byte strings encoded for SSL. Encoding is a byte
|
/// Convert a set of byte slices into a series of byte strings encoded for SSL. Encoding is a byte
|
||||||
/// containing the length followed by the string.
|
/// containing the length followed by the string.
|
||||||
#[cfg(any(feature = "npn", feature = "alpn"))]
|
#[cfg(any(feature = "npn", feature = "alpn"))]
|
||||||
fn ssl_encode_byte_strings(strings: &[&[u8]]) -> Vec<u8>
|
fn ssl_encode_byte_strings(strings: &[&[u8]]) -> Vec<u8> {
|
||||||
{
|
|
||||||
let mut enc = Vec::new();
|
let mut enc = Vec::new();
|
||||||
for string in strings {
|
for string in strings {
|
||||||
let len = string.len() as u8;
|
let len = string.len() as u8;
|
||||||
|
|
@ -453,14 +459,12 @@ fn ssl_encode_byte_strings(strings: &[&[u8]]) -> Vec<u8>
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The signature of functions that can be used to manually verify certificates
|
/// The signature of functions that can be used to manually verify certificates
|
||||||
pub type VerifyCallback = fn(preverify_ok: bool,
|
pub type VerifyCallback = fn(preverify_ok: bool, x509_ctx: &X509StoreContext) -> bool;
|
||||||
x509_ctx: &X509StoreContext) -> bool;
|
|
||||||
|
|
||||||
/// The signature of functions that can be used to manually verify certificates
|
/// The signature of functions that can be used to manually verify certificates
|
||||||
/// when user-data should be carried for all verification process
|
/// when user-data should be carried for all verification process
|
||||||
pub type VerifyCallbackData<T> = fn(preverify_ok: bool,
|
pub type VerifyCallbackData<T> = fn(preverify_ok: bool, x509_ctx: &X509StoreContext, data: &T)
|
||||||
x509_ctx: &X509StoreContext,
|
-> bool;
|
||||||
data: &T) -> bool;
|
|
||||||
|
|
||||||
/// The signature of functions that can be used to choose the context depending on the server name
|
/// The signature of functions that can be used to choose the context depending on the server name
|
||||||
pub type ServerNameCallback = fn(ssl: &mut Ssl, ad: &mut i32) -> i32;
|
pub type ServerNameCallback = fn(ssl: &mut Ssl, ad: &mut i32) -> i32;
|
||||||
|
|
@ -469,7 +473,7 @@ pub type ServerNameCallbackData<T> = fn(ssl: &mut Ssl, ad: &mut i32, data: &T) -
|
||||||
|
|
||||||
// FIXME: macro may be instead of inlining?
|
// FIXME: macro may be instead of inlining?
|
||||||
#[inline]
|
#[inline]
|
||||||
fn wrap_ssl_result(res: c_int) -> Result<(),SslError> {
|
fn wrap_ssl_result(res: c_int) -> Result<(), SslError> {
|
||||||
if res == 0 {
|
if res == 0 {
|
||||||
Err(SslError::get())
|
Err(SslError::get())
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -479,7 +483,7 @@ fn wrap_ssl_result(res: c_int) -> Result<(),SslError> {
|
||||||
|
|
||||||
/// An SSL context object
|
/// An SSL context object
|
||||||
pub struct SslContext {
|
pub struct SslContext {
|
||||||
ctx: *mut ffi::SSL_CTX
|
ctx: *mut ffi::SSL_CTX,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl Send for SslContext {}
|
unsafe impl Send for SslContext {}
|
||||||
|
|
@ -515,13 +519,10 @@ impl SslContext {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Configures the certificate verification method for new connections.
|
/// Configures the certificate verification method for new connections.
|
||||||
pub fn set_verify(&mut self, mode: SslVerifyMode,
|
pub fn set_verify(&mut self, mode: SslVerifyMode, verify: Option<VerifyCallback>) {
|
||||||
verify: Option<VerifyCallback>) {
|
|
||||||
unsafe {
|
unsafe {
|
||||||
ffi::SSL_CTX_set_ex_data(self.ctx, VERIFY_IDX,
|
ffi::SSL_CTX_set_ex_data(self.ctx, VERIFY_IDX, mem::transmute(verify));
|
||||||
mem::transmute(verify));
|
let f: extern "C" fn(c_int, *mut ffi::X509_STORE_CTX) -> c_int = raw_verify;
|
||||||
let f: extern fn(c_int, *mut ffi::X509_STORE_CTX) -> c_int =
|
|
||||||
raw_verify;
|
|
||||||
|
|
||||||
ffi::SSL_CTX_set_verify(self.ctx, mode.bits as c_int, Some(f));
|
ffi::SSL_CTX_set_verify(self.ctx, mode.bits as c_int, Some(f));
|
||||||
}
|
}
|
||||||
|
|
@ -531,18 +532,18 @@ impl SslContext {
|
||||||
/// carrying supplied data.
|
/// carrying supplied data.
|
||||||
// Note: no option because there is no point to set data without providing
|
// Note: no option because there is no point to set data without providing
|
||||||
// a function handling it
|
// a function handling it
|
||||||
pub fn set_verify_with_data<T>(&mut self, mode: SslVerifyMode,
|
pub fn set_verify_with_data<T>(&mut self,
|
||||||
|
mode: SslVerifyMode,
|
||||||
verify: VerifyCallbackData<T>,
|
verify: VerifyCallbackData<T>,
|
||||||
data: T)
|
data: T)
|
||||||
where T: Any + 'static {
|
where T: Any + 'static
|
||||||
|
{
|
||||||
let data = Box::new(data);
|
let data = Box::new(data);
|
||||||
unsafe {
|
unsafe {
|
||||||
ffi::SSL_CTX_set_ex_data(self.ctx, VERIFY_IDX,
|
ffi::SSL_CTX_set_ex_data(self.ctx, VERIFY_IDX, mem::transmute(Some(verify)));
|
||||||
mem::transmute(Some(verify)));
|
ffi::SSL_CTX_set_ex_data(self.ctx, get_verify_data_idx::<T>(), mem::transmute(data));
|
||||||
ffi::SSL_CTX_set_ex_data(self.ctx, get_verify_data_idx::<T>(),
|
let f: extern "C" fn(c_int, *mut ffi::X509_STORE_CTX) -> c_int =
|
||||||
mem::transmute(data));
|
raw_verify_with_data::<T>;
|
||||||
let f: extern fn(c_int, *mut ffi::X509_STORE_CTX) -> c_int =
|
|
||||||
raw_verify_with_data::<T>;
|
|
||||||
|
|
||||||
ffi::SSL_CTX_set_verify(self.ctx, mode.bits as c_int, Some(f));
|
ffi::SSL_CTX_set_verify(self.ctx, mode.bits as c_int, Some(f));
|
||||||
}
|
}
|
||||||
|
|
@ -554,25 +555,25 @@ impl SslContext {
|
||||||
/// with `set_ssl_context`
|
/// with `set_ssl_context`
|
||||||
pub fn set_servername_callback(&mut self, callback: Option<ServerNameCallback>) {
|
pub fn set_servername_callback(&mut self, callback: Option<ServerNameCallback>) {
|
||||||
unsafe {
|
unsafe {
|
||||||
ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX,
|
ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX, mem::transmute(callback));
|
||||||
mem::transmute(callback));
|
let f: extern "C" fn() = mem::transmute(raw_sni);
|
||||||
let f: extern fn() = mem::transmute(raw_sni);
|
|
||||||
ffi_extras::SSL_CTX_set_tlsext_servername_callback(self.ctx, Some(f));
|
ffi_extras::SSL_CTX_set_tlsext_servername_callback(self.ctx, Some(f));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Configures the server name indication (SNI) callback for new connections
|
/// Configures the server name indication (SNI) callback for new connections
|
||||||
/// carrying supplied data
|
/// carrying supplied data
|
||||||
pub fn set_servername_callback_with_data<T>(&mut self, callback: ServerNameCallbackData<T>,
|
pub fn set_servername_callback_with_data<T>(&mut self,
|
||||||
data: T)
|
callback: ServerNameCallbackData<T>,
|
||||||
where T: Any + 'static {
|
data: T)
|
||||||
|
where T: Any + 'static
|
||||||
|
{
|
||||||
let data = Box::new(data);
|
let data = Box::new(data);
|
||||||
unsafe {
|
unsafe {
|
||||||
ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX,
|
ffi::SSL_CTX_set_ex_data(self.ctx, SNI_IDX, mem::transmute(Some(callback)));
|
||||||
mem::transmute(Some(callback)));
|
|
||||||
|
|
||||||
ffi_extras::SSL_CTX_set_tlsext_servername_arg(self.ctx, mem::transmute(data));
|
ffi_extras::SSL_CTX_set_tlsext_servername_arg(self.ctx, mem::transmute(data));
|
||||||
let f: extern fn() = mem::transmute(raw_sni_with_data::<T>);
|
let f: extern "C" fn() = mem::transmute(raw_sni_with_data::<T>);
|
||||||
ffi_extras::SSL_CTX_set_tlsext_servername_callback(self.ctx, Some(f));
|
ffi_extras::SSL_CTX_set_tlsext_servername_callback(self.ctx, Some(f));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -590,91 +591,86 @@ impl SslContext {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_tmp_dh(&self, dh: DH) -> Result<(),SslError> {
|
pub fn set_tmp_dh(&self, dh: DH) -> Result<(), SslError> {
|
||||||
wrap_ssl_result(unsafe {
|
wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_tmp_dh(self.ctx, dh.raw()) as i32 })
|
||||||
ffi_extras::SSL_CTX_set_tmp_dh(self.ctx, dh.raw()) as i32
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(non_snake_case)]
|
#[allow(non_snake_case)]
|
||||||
/// Specifies the file that contains trusted CA certificates.
|
/// Specifies the file that contains trusted CA certificates.
|
||||||
pub fn set_CA_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(),SslError> {
|
pub fn set_CA_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), SslError> {
|
||||||
let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap();
|
let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap();
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe {
|
||||||
unsafe {
|
ffi::SSL_CTX_load_verify_locations(self.ctx, file.as_ptr() as *const _, ptr::null())
|
||||||
ffi::SSL_CTX_load_verify_locations(self.ctx, file.as_ptr() as *const _, ptr::null())
|
})
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specifies the file that contains certificate
|
/// Specifies the file that contains certificate
|
||||||
pub fn set_certificate_file<P: AsRef<Path>>(&mut self, file: P, file_type: X509FileType)
|
pub fn set_certificate_file<P: AsRef<Path>>(&mut self,
|
||||||
-> Result<(),SslError> {
|
file: P,
|
||||||
|
file_type: X509FileType)
|
||||||
|
-> Result<(), SslError> {
|
||||||
let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap();
|
let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap();
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe {
|
||||||
unsafe {
|
ffi::SSL_CTX_use_certificate_file(self.ctx,
|
||||||
ffi::SSL_CTX_use_certificate_file(self.ctx, file.as_ptr() as *const _, file_type as c_int)
|
file.as_ptr() as *const _,
|
||||||
})
|
file_type as c_int)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specifies the file that contains certificate chain
|
/// Specifies the file that contains certificate chain
|
||||||
pub fn set_certificate_chain_file<P: AsRef<Path>>(&mut self, file: P, file_type: X509FileType)
|
pub fn set_certificate_chain_file<P: AsRef<Path>>(&mut self,
|
||||||
-> Result<(),SslError> {
|
file: P,
|
||||||
|
file_type: X509FileType)
|
||||||
|
-> Result<(), SslError> {
|
||||||
let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap();
|
let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap();
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe {
|
||||||
unsafe {
|
ffi::SSL_CTX_use_certificate_chain_file(self.ctx,
|
||||||
ffi::SSL_CTX_use_certificate_chain_file(self.ctx, file.as_ptr() as *const _, file_type as c_int)
|
file.as_ptr() as *const _,
|
||||||
})
|
file_type as c_int)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specifies the certificate
|
/// Specifies the certificate
|
||||||
pub fn set_certificate(&mut self, cert: &X509) -> Result<(),SslError> {
|
pub fn set_certificate(&mut self, cert: &X509) -> Result<(), SslError> {
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe { ffi::SSL_CTX_use_certificate(self.ctx, cert.get_handle()) })
|
||||||
unsafe {
|
|
||||||
ffi::SSL_CTX_use_certificate(self.ctx, cert.get_handle())
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds a certificate to the certificate chain presented together with the
|
/// Adds a certificate to the certificate chain presented together with the
|
||||||
/// certificate specified using set_certificate()
|
/// certificate specified using set_certificate()
|
||||||
pub fn add_extra_chain_cert(&mut self, cert: &X509) -> Result<(),SslError> {
|
pub fn add_extra_chain_cert(&mut self, cert: &X509) -> Result<(), SslError> {
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe {
|
||||||
unsafe {
|
ffi_extras::SSL_CTX_add_extra_chain_cert(self.ctx, cert.get_handle()) as c_int
|
||||||
ffi_extras::SSL_CTX_add_extra_chain_cert(self.ctx, cert.get_handle()) as c_int
|
})
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specifies the file that contains private key
|
/// Specifies the file that contains private key
|
||||||
pub fn set_private_key_file<P: AsRef<Path>>(&mut self, file: P,
|
pub fn set_private_key_file<P: AsRef<Path>>(&mut self,
|
||||||
file_type: X509FileType) -> Result<(),SslError> {
|
file: P,
|
||||||
|
file_type: X509FileType)
|
||||||
|
-> Result<(), SslError> {
|
||||||
let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap();
|
let file = CString::new(file.as_ref().as_os_str().to_str().expect("invalid utf8")).unwrap();
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe {
|
||||||
unsafe {
|
ffi::SSL_CTX_use_PrivateKey_file(self.ctx,
|
||||||
ffi::SSL_CTX_use_PrivateKey_file(self.ctx, file.as_ptr() as *const _, file_type as c_int)
|
file.as_ptr() as *const _,
|
||||||
})
|
file_type as c_int)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Specifies the private key
|
/// Specifies the private key
|
||||||
pub fn set_private_key(&mut self, key: &PKey) -> Result<(),SslError> {
|
pub fn set_private_key(&mut self, key: &PKey) -> Result<(), SslError> {
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe { ffi::SSL_CTX_use_PrivateKey(self.ctx, key.get_handle()) })
|
||||||
unsafe {
|
|
||||||
ffi::SSL_CTX_use_PrivateKey(self.ctx, key.get_handle())
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check consistency of private key and certificate
|
/// Check consistency of private key and certificate
|
||||||
pub fn check_private_key(&mut self) -> Result<(),SslError> {
|
pub fn check_private_key(&mut self) -> Result<(), SslError> {
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe { ffi::SSL_CTX_check_private_key(self.ctx) })
|
||||||
unsafe {
|
|
||||||
ffi::SSL_CTX_check_private_key(self.ctx)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(),SslError> {
|
pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), SslError> {
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe {
|
||||||
unsafe {
|
let cipher_list = CString::new(cipher_list).unwrap();
|
||||||
let cipher_list = CString::new(cipher_list).unwrap();
|
ffi::SSL_CTX_set_cipher_list(self.ctx, cipher_list.as_ptr() as *const _)
|
||||||
ffi::SSL_CTX_set_cipher_list(self.ctx, cipher_list.as_ptr() as *const _)
|
})
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// If `onoff` is set to `true`, enable ECDHE for key exchange with compatible
|
/// If `onoff` is set to `true`, enable ECDHE for key exchange with compatible
|
||||||
|
|
@ -682,33 +678,24 @@ impl SslContext {
|
||||||
///
|
///
|
||||||
/// This method requires OpenSSL >= 1.0.2 or LibreSSL and the `ecdh_auto` feature.
|
/// This method requires OpenSSL >= 1.0.2 or LibreSSL and the `ecdh_auto` feature.
|
||||||
#[cfg(feature = "ecdh_auto")]
|
#[cfg(feature = "ecdh_auto")]
|
||||||
pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(),SslError> {
|
pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), SslError> {
|
||||||
wrap_ssl_result(
|
wrap_ssl_result(unsafe { ffi_extras::SSL_CTX_set_ecdh_auto(self.ctx, onoff as c_int) })
|
||||||
unsafe {
|
|
||||||
ffi_extras::SSL_CTX_set_ecdh_auto(self.ctx, onoff as c_int)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_options(&mut self, option: SslContextOptions) -> SslContextOptions {
|
pub fn set_options(&mut self, option: SslContextOptions) -> SslContextOptions {
|
||||||
let raw_bits = option.bits();
|
let raw_bits = option.bits();
|
||||||
let ret = unsafe {
|
let ret = unsafe { ffi_extras::SSL_CTX_set_options(self.ctx, raw_bits) };
|
||||||
ffi_extras::SSL_CTX_set_options(self.ctx, raw_bits)
|
|
||||||
};
|
|
||||||
SslContextOptions::from_bits(ret).unwrap()
|
SslContextOptions::from_bits(ret).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_options(&mut self) -> SslContextOptions {
|
pub fn get_options(&mut self) -> SslContextOptions {
|
||||||
let ret = unsafe {
|
let ret = unsafe { ffi_extras::SSL_CTX_get_options(self.ctx) };
|
||||||
ffi_extras::SSL_CTX_get_options(self.ctx)
|
|
||||||
};
|
|
||||||
SslContextOptions::from_bits(ret).unwrap()
|
SslContextOptions::from_bits(ret).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn clear_options(&mut self, option: SslContextOptions) -> SslContextOptions {
|
pub fn clear_options(&mut self, option: SslContextOptions) -> SslContextOptions {
|
||||||
let raw_bits = option.bits();
|
let raw_bits = option.bits();
|
||||||
let ret = unsafe {
|
let ret = unsafe { ffi_extras::SSL_CTX_clear_options(self.ctx, raw_bits) };
|
||||||
ffi_extras::SSL_CTX_clear_options(self.ctx, raw_bits)
|
|
||||||
};
|
|
||||||
SslContextOptions::from_bits(ret).unwrap()
|
SslContextOptions::from_bits(ret).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -725,15 +712,18 @@ impl SslContext {
|
||||||
unsafe {
|
unsafe {
|
||||||
// Attach the protocol list to the OpenSSL context structure,
|
// Attach the protocol list to the OpenSSL context structure,
|
||||||
// so that we can refer to it within the callback.
|
// so that we can refer to it within the callback.
|
||||||
ffi::SSL_CTX_set_ex_data(self.ctx, *NPN_PROTOS_IDX,
|
ffi::SSL_CTX_set_ex_data(self.ctx, *NPN_PROTOS_IDX, mem::transmute(protocols));
|
||||||
mem::transmute(protocols));
|
|
||||||
// Now register the callback that performs the default protocol
|
// Now register the callback that performs the default protocol
|
||||||
// matching based on the client-supported list of protocols that
|
// matching based on the client-supported list of protocols that
|
||||||
// has been saved.
|
// has been saved.
|
||||||
ffi::SSL_CTX_set_next_proto_select_cb(self.ctx, raw_next_proto_select_cb, ptr::null_mut());
|
ffi::SSL_CTX_set_next_proto_select_cb(self.ctx,
|
||||||
|
raw_next_proto_select_cb,
|
||||||
|
ptr::null_mut());
|
||||||
// Also register the callback to advertise these protocols, if a server socket is
|
// Also register the callback to advertise these protocols, if a server socket is
|
||||||
// created with the context.
|
// created with the context.
|
||||||
ffi::SSL_CTX_set_next_protos_advertised_cb(self.ctx, raw_next_protos_advertise_cb, ptr::null_mut());
|
ffi::SSL_CTX_set_next_protos_advertised_cb(self.ctx,
|
||||||
|
raw_next_protos_advertise_cb,
|
||||||
|
ptr::null_mut());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -756,8 +746,7 @@ impl SslContext {
|
||||||
// ssl ctx's ex_data so that we can configure a function to free it later. In the
|
// ssl ctx's ex_data so that we can configure a function to free it later. In the
|
||||||
// future, it might make sense to pull this into our internal struct Ssl instead of
|
// future, it might make sense to pull this into our internal struct Ssl instead of
|
||||||
// leaning on openssl and using function pointers.
|
// leaning on openssl and using function pointers.
|
||||||
ffi::SSL_CTX_set_ex_data(self.ctx, *ALPN_PROTOS_IDX,
|
ffi::SSL_CTX_set_ex_data(self.ctx, *ALPN_PROTOS_IDX, mem::transmute(protocols));
|
||||||
mem::transmute(protocols));
|
|
||||||
|
|
||||||
// Now register the callback that performs the default protocol
|
// Now register the callback that performs the default protocol
|
||||||
// matching based on the client-supported list of protocols that
|
// matching based on the client-supported list of protocols that
|
||||||
|
|
@ -765,11 +754,10 @@ impl SslContext {
|
||||||
ffi::SSL_CTX_set_alpn_select_cb(self.ctx, raw_alpn_select_cb, ptr::null_mut());
|
ffi::SSL_CTX_set_alpn_select_cb(self.ctx, raw_alpn_select_cb, ptr::null_mut());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Ssl {
|
pub struct Ssl {
|
||||||
ssl: *mut ffi::SSL
|
ssl: *mut ffi::SSL,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl Send for Ssl {}
|
unsafe impl Send for Ssl {}
|
||||||
|
|
@ -778,8 +766,8 @@ unsafe impl Sync for Ssl {}
|
||||||
impl fmt::Debug for Ssl {
|
impl fmt::Debug for Ssl {
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||||
fmt.debug_struct("Ssl")
|
fmt.debug_struct("Ssl")
|
||||||
.field("state", &self.state_string_long())
|
.field("state", &self.state_string_long())
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -830,7 +818,7 @@ impl Ssl {
|
||||||
let err = unsafe { ffi::SSL_get_error(self.ssl, ret) };
|
let err = unsafe { ffi::SSL_get_error(self.ssl, ret) };
|
||||||
match LibSslError::from_i32(err as i32) {
|
match LibSslError::from_i32(err as i32) {
|
||||||
Some(err) => err,
|
Some(err) => err,
|
||||||
None => unreachable!()
|
None => unreachable!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -855,7 +843,9 @@ impl Ssl {
|
||||||
/// Sets the host name to be used with SNI (Server Name Indication).
|
/// Sets the host name to be used with SNI (Server Name Indication).
|
||||||
pub fn set_hostname(&self, hostname: &str) -> Result<(), SslError> {
|
pub fn set_hostname(&self, hostname: &str) -> Result<(), SslError> {
|
||||||
let cstr = CString::new(hostname).unwrap();
|
let cstr = CString::new(hostname).unwrap();
|
||||||
let ret = unsafe { ffi_extras::SSL_set_tlsext_host_name(self.ssl, cstr.as_ptr() as *const _) };
|
let ret = unsafe {
|
||||||
|
ffi_extras::SSL_set_tlsext_host_name(self.ssl, cstr.as_ptr() as *const _)
|
||||||
|
};
|
||||||
|
|
||||||
// For this case, 0 indicates failure.
|
// For this case, 0 indicates failure.
|
||||||
if ret == 0 {
|
if ret == 0 {
|
||||||
|
|
@ -926,9 +916,7 @@ impl Ssl {
|
||||||
/// Returns the number of bytes remaining in the currently processed TLS
|
/// Returns the number of bytes remaining in the currently processed TLS
|
||||||
/// record.
|
/// record.
|
||||||
pub fn pending(&self) -> usize {
|
pub fn pending(&self) -> usize {
|
||||||
unsafe {
|
unsafe { ffi::SSL_pending(self.ssl) as usize }
|
||||||
ffi::SSL_pending(self.ssl) as usize
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the compression currently in use.
|
/// Returns the compression currently in use.
|
||||||
|
|
@ -963,9 +951,7 @@ impl Ssl {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe {
|
unsafe { String::from_utf8(CStr::from_ptr(name as *const _).to_bytes().to_vec()).ok() }
|
||||||
String::from_utf8(CStr::from_ptr(name).to_bytes().to_vec()).ok()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// change the context corresponding to the current connection
|
/// change the context corresponding to the current connection
|
||||||
|
|
@ -1038,12 +1024,13 @@ impl<S> Drop for SslStream<S> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> fmt::Debug for SslStream<S> where S: fmt::Debug {
|
impl<S> fmt::Debug for SslStream<S> where S: fmt::Debug
|
||||||
|
{
|
||||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||||
fmt.debug_struct("SslStream")
|
fmt.debug_struct("SslStream")
|
||||||
.field("stream", &self.get_ref())
|
.field("stream", &self.get_ref())
|
||||||
.field("ssl", &self.ssl())
|
.field("ssl", &self.ssl())
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1061,7 +1048,7 @@ impl<S: AsRawSocket> AsRawSocket for SslStream<S> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Read+Write> SslStream<S> {
|
impl<S: Read + Write> SslStream<S> {
|
||||||
fn new_base(ssl: Ssl, stream: S) -> Self {
|
fn new_base(ssl: Ssl, stream: S) -> Self {
|
||||||
unsafe {
|
unsafe {
|
||||||
let (bio, method) = bio::new(stream).unwrap();
|
let (bio, method) = bio::new(stream).unwrap();
|
||||||
|
|
@ -1083,16 +1070,10 @@ impl<S: Read+Write> SslStream<S> {
|
||||||
if ret > 0 {
|
if ret > 0 {
|
||||||
Ok(stream)
|
Ok(stream)
|
||||||
} else {
|
} else {
|
||||||
match stream.make_old_error(ret) {
|
match stream.make_error(ret) {
|
||||||
SslError::StreamError(e) => {
|
// This is fine - nonblocking sockets will finish the handshake in read/write
|
||||||
// This is fine - nonblocking sockets will finish the handshake in read/write
|
Error::WantRead(..) | Error::WantWrite(..) => Ok(stream),
|
||||||
if e.kind() == io::ErrorKind::WouldBlock {
|
_ => Err(stream.make_old_error(ret)),
|
||||||
Ok(stream)
|
|
||||||
} else {
|
|
||||||
Err(SslError::StreamError(e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
e => Err(e)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1105,16 +1086,10 @@ impl<S: Read+Write> SslStream<S> {
|
||||||
if ret > 0 {
|
if ret > 0 {
|
||||||
Ok(stream)
|
Ok(stream)
|
||||||
} else {
|
} else {
|
||||||
match stream.make_old_error(ret) {
|
match stream.make_error(ret) {
|
||||||
SslError::StreamError(e) => {
|
// This is fine - nonblocking sockets will finish the handshake in read/write
|
||||||
// This is fine - nonblocking sockets will finish the handshake in read/write
|
Error::WantRead(..) | Error::WantWrite(..) => Ok(stream),
|
||||||
if e.kind() == io::ErrorKind::WouldBlock {
|
_ => Err(stream.make_old_error(ret)),
|
||||||
Ok(stream)
|
|
||||||
} else {
|
|
||||||
Err(SslError::StreamError(e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
e => Err(e)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1132,91 +1107,6 @@ impl<S: Read+Write> SslStream<S> {
|
||||||
pub fn accept_generic<T: IntoSsl>(ssl: T, stream: S) -> Result<SslStream<S>, SslError> {
|
pub fn accept_generic<T: IntoSsl>(ssl: T, stream: S) -> Result<SslStream<S>, SslError> {
|
||||||
Self::accept(ssl, stream)
|
Self::accept(ssl, stream)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl<S> SslStream<S> {
|
|
||||||
fn make_error(&mut self, ret: c_int) -> Error {
|
|
||||||
match self.ssl.get_error(ret) {
|
|
||||||
LibSslError::ErrorSsl => Error::Ssl(OpenSslError::get_stack()),
|
|
||||||
LibSslError::ErrorSyscall => {
|
|
||||||
let errs = OpenSslError::get_stack();
|
|
||||||
if errs.is_empty() {
|
|
||||||
if ret == 0 {
|
|
||||||
Error::Stream(io::Error::new(io::ErrorKind::ConnectionAborted,
|
|
||||||
"unexpected EOF observed"))
|
|
||||||
} else {
|
|
||||||
Error::Stream(self.get_bio_error())
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Error::Ssl(errs)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LibSslError::ErrorZeroReturn => Error::ZeroReturn,
|
|
||||||
LibSslError::ErrorWantWrite => Error::WantWrite(self.get_bio_error()),
|
|
||||||
LibSslError::ErrorWantRead => Error::WantRead(self.get_bio_error()),
|
|
||||||
err => Error::Stream(io::Error::new(io::ErrorKind::Other,
|
|
||||||
format!("unexpected error {:?}", err))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_old_error(&mut self, ret: c_int) -> SslError {
|
|
||||||
match self.ssl.get_error(ret) {
|
|
||||||
LibSslError::ErrorSsl => SslError::get(),
|
|
||||||
LibSslError::ErrorSyscall => {
|
|
||||||
let err = SslError::get();
|
|
||||||
let count = match err {
|
|
||||||
SslError::OpenSslErrors(ref v) => v.len(),
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
if count == 0 {
|
|
||||||
if ret == 0 {
|
|
||||||
SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted,
|
|
||||||
"unexpected EOF observed"))
|
|
||||||
} else {
|
|
||||||
SslError::StreamError(self.get_bio_error())
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
LibSslError::ErrorZeroReturn => SslError::SslSessionClosed,
|
|
||||||
LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => {
|
|
||||||
SslError::StreamError(self.get_bio_error())
|
|
||||||
}
|
|
||||||
err => SslError::StreamError(io::Error::new(io::ErrorKind::Other,
|
|
||||||
format!("unexpected error {:?}", err))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_bio_error(&mut self) -> io::Error {
|
|
||||||
let error = unsafe { bio::take_error::<S>(self.ssl.get_raw_rbio()) };
|
|
||||||
match error {
|
|
||||||
Some(error) => error,
|
|
||||||
None => io::Error::new(io::ErrorKind::Other,
|
|
||||||
"BUG: got an ErrorSyscall without an error in the BIO?")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a reference to the underlying stream.
|
|
||||||
pub fn get_ref(&self) -> &S {
|
|
||||||
unsafe {
|
|
||||||
let bio = self.ssl.get_raw_rbio();
|
|
||||||
bio::get_ref(bio)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a mutable reference to the underlying stream.
|
|
||||||
///
|
|
||||||
/// ## Warning
|
|
||||||
///
|
|
||||||
/// It is inadvisable to read from or write to the underlying stream as it
|
|
||||||
/// will most likely corrupt the SSL session.
|
|
||||||
pub fn get_mut(&mut self) -> &mut S {
|
|
||||||
unsafe {
|
|
||||||
let bio = self.ssl.get_raw_rbio();
|
|
||||||
bio::get_mut(bio)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Like `read`, but returns an `ssl::Error` rather than an `io::Error`.
|
/// Like `read`, but returns an `ssl::Error` rather than an `io::Error`.
|
||||||
///
|
///
|
||||||
|
|
@ -1243,6 +1133,97 @@ impl<S> SslStream<S> {
|
||||||
Err(self.make_error(ret))
|
Err(self.make_error(ret))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> SslStream<S> {
|
||||||
|
fn make_error(&mut self, ret: c_int) -> Error {
|
||||||
|
match self.ssl.get_error(ret) {
|
||||||
|
LibSslError::ErrorSsl => Error::Ssl(OpenSslError::get_stack()),
|
||||||
|
LibSslError::ErrorSyscall => {
|
||||||
|
let errs = OpenSslError::get_stack();
|
||||||
|
if errs.is_empty() {
|
||||||
|
if ret == 0 {
|
||||||
|
Error::Stream(io::Error::new(io::ErrorKind::ConnectionAborted,
|
||||||
|
"unexpected EOF observed"))
|
||||||
|
} else {
|
||||||
|
Error::Stream(self.get_bio_error())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Error::Ssl(errs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LibSslError::ErrorZeroReturn => Error::ZeroReturn,
|
||||||
|
LibSslError::ErrorWantWrite => Error::WantWrite(self.get_bio_error()),
|
||||||
|
LibSslError::ErrorWantRead => Error::WantRead(self.get_bio_error()),
|
||||||
|
err => {
|
||||||
|
Error::Stream(io::Error::new(io::ErrorKind::Other,
|
||||||
|
format!("unexpected error {:?}", err)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_old_error(&mut self, ret: c_int) -> SslError {
|
||||||
|
match self.ssl.get_error(ret) {
|
||||||
|
LibSslError::ErrorSsl => SslError::get(),
|
||||||
|
LibSslError::ErrorSyscall => {
|
||||||
|
let err = SslError::get();
|
||||||
|
let count = match err {
|
||||||
|
SslError::OpenSslErrors(ref v) => v.len(),
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
if count == 0 {
|
||||||
|
if ret == 0 {
|
||||||
|
SslError::StreamError(io::Error::new(io::ErrorKind::ConnectionAborted,
|
||||||
|
"unexpected EOF observed"))
|
||||||
|
} else {
|
||||||
|
SslError::StreamError(self.get_bio_error())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LibSslError::ErrorZeroReturn => SslError::SslSessionClosed,
|
||||||
|
LibSslError::ErrorWantWrite | LibSslError::ErrorWantRead => {
|
||||||
|
SslError::StreamError(self.get_bio_error())
|
||||||
|
}
|
||||||
|
err => {
|
||||||
|
SslError::StreamError(io::Error::new(io::ErrorKind::Other,
|
||||||
|
format!("unexpected error {:?}", err)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_bio_error(&mut self) -> io::Error {
|
||||||
|
let error = unsafe { bio::take_error::<S>(self.ssl.get_raw_rbio()) };
|
||||||
|
match error {
|
||||||
|
Some(error) => error,
|
||||||
|
None => {
|
||||||
|
io::Error::new(io::ErrorKind::Other,
|
||||||
|
"BUG: got an ErrorSyscall without an error in the BIO?")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a reference to the underlying stream.
|
||||||
|
pub fn get_ref(&self) -> &S {
|
||||||
|
unsafe {
|
||||||
|
let bio = self.ssl.get_raw_rbio();
|
||||||
|
bio::get_ref(bio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a mutable reference to the underlying stream.
|
||||||
|
///
|
||||||
|
/// ## Warning
|
||||||
|
///
|
||||||
|
/// It is inadvisable to read from or write to the underlying stream as it
|
||||||
|
/// will most likely corrupt the SSL session.
|
||||||
|
pub fn get_mut(&mut self) -> &mut S {
|
||||||
|
unsafe {
|
||||||
|
let bio = self.ssl.get_raw_rbio();
|
||||||
|
bio::get_mut(bio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the OpenSSL `Ssl` object associated with this stream.
|
/// Returns the OpenSSL `Ssl` object associated with this stream.
|
||||||
pub fn ssl(&self) -> &Ssl {
|
pub fn ssl(&self) -> &Ssl {
|
||||||
|
|
@ -1258,7 +1239,7 @@ impl SslStream<::std::net::TcpStream> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Read> Read for SslStream<S> {
|
impl<S: Read + Write> Read for SslStream<S> {
|
||||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
match self.ssl_read(buf) {
|
match self.ssl_read(buf) {
|
||||||
Ok(n) => Ok(n),
|
Ok(n) => Ok(n),
|
||||||
|
|
@ -1271,7 +1252,7 @@ impl<S: Read> Read for SslStream<S> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Write> Write for SslStream<S> {
|
impl<S: Read + Write> Write for SslStream<S> {
|
||||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
self.ssl_write(buf).map_err(|e| {
|
self.ssl_write(buf).map_err(|e| {
|
||||||
match e {
|
match e {
|
||||||
|
|
@ -1306,14 +1287,17 @@ impl<'a> IntoSsl for &'a SslContext {
|
||||||
|
|
||||||
/// A utility type to help in cases where the use of SSL is decided at runtime.
|
/// A utility type to help in cases where the use of SSL is decided at runtime.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum MaybeSslStream<S> where S: Read+Write {
|
pub enum MaybeSslStream<S>
|
||||||
|
where S: Read + Write
|
||||||
|
{
|
||||||
/// A connection using SSL
|
/// A connection using SSL
|
||||||
Ssl(SslStream<S>),
|
Ssl(SslStream<S>),
|
||||||
/// A connection not using SSL
|
/// A connection not using SSL
|
||||||
Normal(S),
|
Normal(S),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> Read for MaybeSslStream<S> where S: Read+Write {
|
impl<S> Read for MaybeSslStream<S> where S: Read + Write
|
||||||
|
{
|
||||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
match *self {
|
match *self {
|
||||||
MaybeSslStream::Ssl(ref mut s) => s.read(buf),
|
MaybeSslStream::Ssl(ref mut s) => s.read(buf),
|
||||||
|
|
@ -1322,7 +1306,8 @@ impl<S> Read for MaybeSslStream<S> where S: Read+Write {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> Write for MaybeSslStream<S> where S: Read+Write {
|
impl<S> Write for MaybeSslStream<S> where S: Read + Write
|
||||||
|
{
|
||||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
match *self {
|
match *self {
|
||||||
MaybeSslStream::Ssl(ref mut s) => s.write(buf),
|
MaybeSslStream::Ssl(ref mut s) => s.write(buf),
|
||||||
|
|
@ -1338,7 +1323,8 @@ impl<S> Write for MaybeSslStream<S> where S: Read+Write {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> MaybeSslStream<S> where S: Read+Write {
|
impl<S> MaybeSslStream<S> where S: Read + Write
|
||||||
|
{
|
||||||
/// Returns a reference to the underlying stream.
|
/// Returns a reference to the underlying stream.
|
||||||
pub fn get_ref(&self) -> &S {
|
pub fn get_ref(&self) -> &S {
|
||||||
match *self {
|
match *self {
|
||||||
|
|
@ -1423,7 +1409,7 @@ impl<S> NonblockingSslStream<S> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Read+Write> NonblockingSslStream<S> {
|
impl<S: Read + Write> NonblockingSslStream<S> {
|
||||||
/// Create a new nonblocking client ssl connection on wrapped `stream`.
|
/// Create a new nonblocking client ssl connection on wrapped `stream`.
|
||||||
///
|
///
|
||||||
/// Note that this method will most likely not actually complete the SSL
|
/// Note that this method will most likely not actually complete the SSL
|
||||||
|
|
@ -1453,7 +1439,7 @@ impl<S: Read+Write> NonblockingSslStream<S> {
|
||||||
SslError::OpenSslErrors(e.iter()
|
SslError::OpenSslErrors(e.iter()
|
||||||
.map(|e| OpensslError::from_error_code(e.error_code()))
|
.map(|e| OpensslError::from_error_code(e.error_code()))
|
||||||
.collect())
|
.collect())
|
||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1477,7 +1463,7 @@ impl<S: Read+Write> NonblockingSslStream<S> {
|
||||||
match self.0.ssl_read(buf) {
|
match self.0.ssl_read(buf) {
|
||||||
Ok(n) => Ok(n),
|
Ok(n) => Ok(n),
|
||||||
Err(Error::ZeroReturn) => Ok(0),
|
Err(Error::ZeroReturn) => Ok(0),
|
||||||
Err(e) => Err(self.convert_err(e))
|
Err(e) => Err(self.convert_err(e)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ use std::thread;
|
||||||
|
|
||||||
use net2::TcpStreamExt;
|
use net2::TcpStreamExt;
|
||||||
|
|
||||||
use crypto::hash::Type::{SHA256};
|
use crypto::hash::Type::SHA256;
|
||||||
use ssl;
|
use ssl;
|
||||||
use ssl::SSL_VERIFY_PEER;
|
use ssl::SSL_VERIFY_PEER;
|
||||||
use ssl::SslMethod::Sslv23;
|
use ssl::SslMethod::Sslv23;
|
||||||
|
|
@ -48,20 +48,24 @@ struct Server {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Server {
|
impl Server {
|
||||||
fn spawn(args: &[&str], input: Option<Box<FnMut(ChildStdin) + Send>>)
|
fn spawn(args: &[&str], input: Option<Box<FnMut(ChildStdin) + Send>>) -> (Server, SocketAddr) {
|
||||||
-> (Server, SocketAddr) {
|
|
||||||
let addr = next_addr();
|
let addr = next_addr();
|
||||||
let mut child = Command::new("openssl").arg("s_server")
|
let mut child = Command::new("openssl")
|
||||||
.arg("-accept").arg(addr.port().to_string())
|
.arg("s_server")
|
||||||
.args(args)
|
.arg("-accept")
|
||||||
.arg("-cert").arg("cert.pem")
|
.arg(addr.port().to_string())
|
||||||
.arg("-key").arg("key.pem")
|
.args(args)
|
||||||
.arg("-no_dhe")
|
.arg("-cert")
|
||||||
.current_dir("test")
|
.arg("cert.pem")
|
||||||
.stdout(Stdio::null())
|
.arg("-key")
|
||||||
.stderr(Stdio::null())
|
.arg("key.pem")
|
||||||
.stdin(Stdio::piped())
|
.arg("-no_dhe")
|
||||||
.spawn().unwrap();
|
.current_dir("test")
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null())
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
let stdin = child.stdin.take().unwrap();
|
let stdin = child.stdin.take().unwrap();
|
||||||
if let Some(mut input) = input {
|
if let Some(mut input) = input {
|
||||||
thread::spawn(move || input(stdin));
|
thread::spawn(move || input(stdin));
|
||||||
|
|
@ -71,7 +75,7 @@ impl Server {
|
||||||
|
|
||||||
fn new_tcp(args: &[&str]) -> (Server, TcpStream) {
|
fn new_tcp(args: &[&str]) -> (Server, TcpStream) {
|
||||||
let (server, addr) = Server::spawn(args, None);
|
let (server, addr) = Server::spawn(args, None);
|
||||||
loop {
|
for _ in 0..20 {
|
||||||
match TcpStream::connect(&addr) {
|
match TcpStream::connect(&addr) {
|
||||||
Ok(s) => return (server, s),
|
Ok(s) => return (server, s),
|
||||||
Err(ref e) if e.kind() == io::ErrorKind::ConnectionRefused => {
|
Err(ref e) if e.kind() == io::ErrorKind::ConnectionRefused => {
|
||||||
|
|
@ -80,6 +84,7 @@ impl Server {
|
||||||
Err(e) => panic!("wut: {}", e),
|
Err(e) => panic!("wut: {}", e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
panic!("server never came online");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn new() -> (Server, TcpStream) {
|
fn new() -> (Server, TcpStream) {
|
||||||
|
|
@ -88,23 +93,27 @@ impl Server {
|
||||||
|
|
||||||
#[cfg(any(feature = "alpn", feature = "npn"))]
|
#[cfg(any(feature = "alpn", feature = "npn"))]
|
||||||
fn new_alpn() -> (Server, TcpStream) {
|
fn new_alpn() -> (Server, TcpStream) {
|
||||||
Server::new_tcp(&["-www", "-nextprotoneg", "http/1.1,spdy/3.1",
|
Server::new_tcp(&["-www",
|
||||||
"-alpn", "http/1.1,spdy/3.1"])
|
"-nextprotoneg",
|
||||||
|
"http/1.1,spdy/3.1",
|
||||||
|
"-alpn",
|
||||||
|
"http/1.1,spdy/3.1"])
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "dtlsv1")]
|
#[cfg(feature = "dtlsv1")]
|
||||||
fn new_dtlsv1<I>(input: I) -> (Server, UdpConnected)
|
fn new_dtlsv1<I>(input: I) -> (Server, UdpConnected)
|
||||||
where I: IntoIterator<Item=&'static str>,
|
where I: IntoIterator<Item = &'static str>,
|
||||||
I::IntoIter: Send + 'static
|
I::IntoIter: Send + 'static
|
||||||
{
|
{
|
||||||
let mut input = input.into_iter();
|
let mut input = input.into_iter();
|
||||||
let (s, addr) = Server::spawn(&["-dtls1"], Some(Box::new(move |mut io| {
|
let (s, addr) = Server::spawn(&["-dtls1"],
|
||||||
for s in input.by_ref() {
|
Some(Box::new(move |mut io| {
|
||||||
if io.write_all(s.as_bytes()).is_err() {
|
for s in input.by_ref() {
|
||||||
break
|
if io.write_all(s.as_bytes()).is_err() {
|
||||||
}
|
break;
|
||||||
}
|
}
|
||||||
})));
|
}
|
||||||
|
})));
|
||||||
// Need to wait for the UDP socket to get bound in our child process,
|
// Need to wait for the UDP socket to get bound in our child process,
|
||||||
// but don't currently have a great way to do that so just wait for a
|
// but don't currently have a great way to do that so just wait for a
|
||||||
// bit.
|
// bit.
|
||||||
|
|
@ -139,8 +148,10 @@ impl Write for UdpConnected {
|
||||||
use std::os::unix::prelude::*;
|
use std::os::unix::prelude::*;
|
||||||
use libc;
|
use libc;
|
||||||
let n = unsafe {
|
let n = unsafe {
|
||||||
libc::send(self.0.as_raw_fd(), buf.as_ptr() as *const _,
|
libc::send(self.0.as_raw_fd(),
|
||||||
buf.len() as libc::size_t, 0)
|
buf.as_ptr() as *const _,
|
||||||
|
buf.len() as libc::size_t,
|
||||||
|
0)
|
||||||
};
|
};
|
||||||
if n < 0 {
|
if n < 0 {
|
||||||
Err(io::Error::last_os_error())
|
Err(io::Error::last_os_error())
|
||||||
|
|
@ -154,8 +165,10 @@ impl Write for UdpConnected {
|
||||||
use std::os::windows::prelude::*;
|
use std::os::windows::prelude::*;
|
||||||
use libc;
|
use libc;
|
||||||
let n = unsafe {
|
let n = unsafe {
|
||||||
libc::send(self.0.as_raw_socket(), buf.as_ptr() as *const _,
|
libc::send(self.0.as_raw_socket(),
|
||||||
buf.len() as libc::c_int, 0)
|
buf.as_ptr() as *const _,
|
||||||
|
buf.len() as libc::c_int,
|
||||||
|
0)
|
||||||
};
|
};
|
||||||
if n < 0 {
|
if n < 0 {
|
||||||
Err(io::Error::last_os_error())
|
Err(io::Error::last_os_error())
|
||||||
|
|
@ -164,7 +177,9 @@ impl Write for UdpConnected {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flush(&mut self) -> io::Result<()> { Ok(()) }
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! run_test(
|
macro_rules! run_test(
|
||||||
|
|
@ -398,11 +413,11 @@ fn test_set_certificate_and_private_key() {
|
||||||
let key_path = Path::new("test/key.pem");
|
let key_path = Path::new("test/key.pem");
|
||||||
let cert_path = Path::new("test/cert.pem");
|
let cert_path = Path::new("test/cert.pem");
|
||||||
let mut key_file = File::open(&key_path)
|
let mut key_file = File::open(&key_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/key.pem`");
|
.expect("Failed to open `test/key.pem`");
|
||||||
let mut cert_file = File::open(&cert_path)
|
let mut cert_file = File::open(&cert_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/cert.pem`");
|
.expect("Failed to open `test/cert.pem`");
|
||||||
|
|
||||||
let key = PKey::private_key_from_pem(&mut key_file).unwrap();
|
let key = PKey::private_key_from_pem(&mut key_file).unwrap();
|
||||||
let cert = X509::from_pem(&mut cert_file).unwrap();
|
let cert = X509::from_pem(&mut cert_file).unwrap();
|
||||||
|
|
@ -467,8 +482,7 @@ run_test!(get_peer_certificate, |method, stream| {
|
||||||
fn test_write_dtlsv1() {
|
fn test_write_dtlsv1() {
|
||||||
let (_s, stream) = Server::new_dtlsv1(iter::repeat("y\n"));
|
let (_s, stream) = Server::new_dtlsv1(iter::repeat("y\n"));
|
||||||
|
|
||||||
let mut stream = SslStream::connect_generic(&SslContext::new(Dtlsv1).unwrap(),
|
let mut stream = SslStream::connect_generic(&SslContext::new(Dtlsv1).unwrap(), stream).unwrap();
|
||||||
stream).unwrap();
|
|
||||||
stream.write_all(b"hello").unwrap();
|
stream.write_all(b"hello").unwrap();
|
||||||
stream.flush().unwrap();
|
stream.flush().unwrap();
|
||||||
stream.write_all(b" there").unwrap();
|
stream.write_all(b" there").unwrap();
|
||||||
|
|
@ -501,7 +515,7 @@ fn test_pending() {
|
||||||
stream.flush().unwrap();
|
stream.flush().unwrap();
|
||||||
|
|
||||||
// wait for the response and read first byte...
|
// wait for the response and read first byte...
|
||||||
let mut buf = [0u8; 16*1024];
|
let mut buf = [0u8; 16 * 1024];
|
||||||
stream.read(&mut buf[..1]).unwrap();
|
stream.read(&mut buf[..1]).unwrap();
|
||||||
|
|
||||||
let pending = stream.ssl().pending();
|
let pending = stream.ssl().pending();
|
||||||
|
|
@ -521,7 +535,8 @@ fn test_state() {
|
||||||
let (_s, tcp) = Server::new();
|
let (_s, tcp) = Server::new();
|
||||||
let stream = SslStream::connect_generic(&SslContext::new(Sslv23).unwrap(), tcp).unwrap();
|
let stream = SslStream::connect_generic(&SslContext::new(Sslv23).unwrap(), tcp).unwrap();
|
||||||
assert_eq!(stream.ssl().state_string(), "SSLOK ");
|
assert_eq!(stream.ssl().state_string(), "SSLOK ");
|
||||||
assert_eq!(stream.ssl().state_string_long(), "SSL negotiation finished successfully");
|
assert_eq!(stream.ssl().state_string_long(),
|
||||||
|
"SSL negotiation finished successfully");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tests that connecting with the client using ALPN, but the server not does not
|
/// Tests that connecting with the client using ALPN, but the server not does not
|
||||||
|
|
@ -535,11 +550,11 @@ fn test_connect_with_unilateral_alpn() {
|
||||||
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
let stream = match SslStream::connect(&ctx, stream) {
|
let stream = match SslStream::connect(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
// Since the socket to which we connected is not configured to use ALPN,
|
// Since the socket to which we connected is not configured to use ALPN,
|
||||||
// there should be no selected protocol...
|
// there should be no selected protocol...
|
||||||
|
|
@ -557,11 +572,11 @@ fn test_connect_with_unilateral_npn() {
|
||||||
ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
let stream = match SslStream::connect_generic(&ctx, stream) {
|
let stream = match SslStream::connect_generic(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
// Since the socket to which we connected is not configured to use NPN,
|
// Since the socket to which we connected is not configured to use NPN,
|
||||||
// there should be no selected protocol...
|
// there should be no selected protocol...
|
||||||
|
|
@ -579,11 +594,11 @@ fn test_connect_with_alpn_successful_multiple_matching() {
|
||||||
ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]);
|
ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
let stream = match SslStream::connect(&ctx, stream) {
|
let stream = match SslStream::connect(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
// The server prefers "http/1.1", so that is chosen, even though the client
|
// The server prefers "http/1.1", so that is chosen, even though the client
|
||||||
// would prefer "spdy/3.1"
|
// would prefer "spdy/3.1"
|
||||||
|
|
@ -601,11 +616,11 @@ fn test_connect_with_npn_successful_multiple_matching() {
|
||||||
ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]);
|
ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
let stream = match SslStream::connect_generic(&ctx, stream) {
|
let stream = match SslStream::connect_generic(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
// The server prefers "http/1.1", so that is chosen, even though the client
|
// The server prefers "http/1.1", so that is chosen, even though the client
|
||||||
// would prefer "spdy/3.1"
|
// would prefer "spdy/3.1"
|
||||||
|
|
@ -624,11 +639,11 @@ fn test_connect_with_alpn_successful_single_match() {
|
||||||
ctx.set_alpn_protocols(&[b"spdy/3.1"]);
|
ctx.set_alpn_protocols(&[b"spdy/3.1"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
let stream = match SslStream::connect(&ctx, stream) {
|
let stream = match SslStream::connect(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
// The client now only supports one of the server's protocols, so that one
|
// The client now only supports one of the server's protocols, so that one
|
||||||
// is used.
|
// is used.
|
||||||
|
|
@ -648,11 +663,11 @@ fn test_connect_with_npn_successful_single_match() {
|
||||||
ctx.set_npn_protocols(&[b"spdy/3.1"]);
|
ctx.set_npn_protocols(&[b"spdy/3.1"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
let stream = match SslStream::connect_generic(&ctx, stream) {
|
let stream = match SslStream::connect_generic(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
// The client now only supports one of the server's protocols, so that one
|
// The client now only supports one of the server's protocols, so that one
|
||||||
// is used.
|
// is used.
|
||||||
|
|
@ -671,10 +686,10 @@ fn test_npn_server_advertise_multiple() {
|
||||||
let mut ctx = SslContext::new(Sslv23).unwrap();
|
let mut ctx = SslContext::new(Sslv23).unwrap();
|
||||||
ctx.set_verify(SSL_VERIFY_PEER, None);
|
ctx.set_verify(SSL_VERIFY_PEER, None);
|
||||||
ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
||||||
assert!(ctx.set_certificate_file(
|
assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM)
|
||||||
&Path::new("test/cert.pem"), X509FileType::PEM).is_ok());
|
.is_ok());
|
||||||
ctx.set_private_key_file(
|
ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM)
|
||||||
&Path::new("test/key.pem"), X509FileType::PEM).unwrap();
|
.unwrap();
|
||||||
ctx
|
ctx
|
||||||
};
|
};
|
||||||
// Have the listener wait on the connection in a different thread.
|
// Have the listener wait on the connection in a different thread.
|
||||||
|
|
@ -688,13 +703,13 @@ fn test_npn_server_advertise_multiple() {
|
||||||
ctx.set_npn_protocols(&[b"spdy/3.1"]);
|
ctx.set_npn_protocols(&[b"spdy/3.1"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
// Now connect to the socket and make sure the protocol negotiation works...
|
// Now connect to the socket and make sure the protocol negotiation works...
|
||||||
let stream = TcpStream::connect(localhost).unwrap();
|
let stream = TcpStream::connect(localhost).unwrap();
|
||||||
let stream = match SslStream::connect_generic(&ctx, stream) {
|
let stream = match SslStream::connect_generic(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
// SPDY is selected since that's the only thing the client supports.
|
// SPDY is selected since that's the only thing the client supports.
|
||||||
assert_eq!(b"spdy/3.1", stream.ssl().selected_npn_protocol().unwrap());
|
assert_eq!(b"spdy/3.1", stream.ssl().selected_npn_protocol().unwrap());
|
||||||
|
|
@ -712,10 +727,10 @@ fn test_alpn_server_advertise_multiple() {
|
||||||
let mut ctx = SslContext::new(Sslv23).unwrap();
|
let mut ctx = SslContext::new(Sslv23).unwrap();
|
||||||
ctx.set_verify(SSL_VERIFY_PEER, None);
|
ctx.set_verify(SSL_VERIFY_PEER, None);
|
||||||
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
||||||
assert!(ctx.set_certificate_file(
|
assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM)
|
||||||
&Path::new("test/cert.pem"), X509FileType::PEM).is_ok());
|
.is_ok());
|
||||||
ctx.set_private_key_file(
|
ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM)
|
||||||
&Path::new("test/key.pem"), X509FileType::PEM).unwrap();
|
.unwrap();
|
||||||
ctx
|
ctx
|
||||||
};
|
};
|
||||||
// Have the listener wait on the connection in a different thread.
|
// Have the listener wait on the connection in a different thread.
|
||||||
|
|
@ -729,13 +744,13 @@ fn test_alpn_server_advertise_multiple() {
|
||||||
ctx.set_alpn_protocols(&[b"spdy/3.1"]);
|
ctx.set_alpn_protocols(&[b"spdy/3.1"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
// Now connect to the socket and make sure the protocol negotiation works...
|
// Now connect to the socket and make sure the protocol negotiation works...
|
||||||
let stream = TcpStream::connect(localhost).unwrap();
|
let stream = TcpStream::connect(localhost).unwrap();
|
||||||
let stream = match SslStream::connect(&ctx, stream) {
|
let stream = match SslStream::connect(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
// SPDY is selected since that's the only thing the client supports.
|
// SPDY is selected since that's the only thing the client supports.
|
||||||
assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap());
|
assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap());
|
||||||
|
|
@ -753,10 +768,10 @@ fn test_alpn_server_select_none() {
|
||||||
let mut ctx = SslContext::new(Sslv23).unwrap();
|
let mut ctx = SslContext::new(Sslv23).unwrap();
|
||||||
ctx.set_verify(SSL_VERIFY_PEER, None);
|
ctx.set_verify(SSL_VERIFY_PEER, None);
|
||||||
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]);
|
||||||
assert!(ctx.set_certificate_file(
|
assert!(ctx.set_certificate_file(&Path::new("test/cert.pem"), X509FileType::PEM)
|
||||||
&Path::new("test/cert.pem"), X509FileType::PEM).is_ok());
|
.is_ok());
|
||||||
ctx.set_private_key_file(
|
ctx.set_private_key_file(&Path::new("test/key.pem"), X509FileType::PEM)
|
||||||
&Path::new("test/key.pem"), X509FileType::PEM).unwrap();
|
.unwrap();
|
||||||
ctx
|
ctx
|
||||||
};
|
};
|
||||||
// Have the listener wait on the connection in a different thread.
|
// Have the listener wait on the connection in a different thread.
|
||||||
|
|
@ -770,13 +785,13 @@ fn test_alpn_server_select_none() {
|
||||||
ctx.set_alpn_protocols(&[b"http/2"]);
|
ctx.set_alpn_protocols(&[b"http/2"]);
|
||||||
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
match ctx.set_CA_file(&Path::new("test/cert.pem")) {
|
||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(err) => panic!("Unexpected error {:?}", err)
|
Err(err) => panic!("Unexpected error {:?}", err),
|
||||||
}
|
}
|
||||||
// Now connect to the socket and make sure the protocol negotiation works...
|
// Now connect to the socket and make sure the protocol negotiation works...
|
||||||
let stream = TcpStream::connect(localhost).unwrap();
|
let stream = TcpStream::connect(localhost).unwrap();
|
||||||
let stream = match SslStream::connect(&ctx, stream) {
|
let stream = match SslStream::connect(&ctx, stream) {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(err) => panic!("Expected success, got {:?}", err)
|
Err(err) => panic!("Expected success, got {:?}", err),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Since the protocols from the server and client don't overlap at all, no protocol is selected
|
// Since the protocols from the server and client don't overlap at all, no protocol is selected
|
||||||
|
|
@ -791,14 +806,14 @@ mod dtlsv1 {
|
||||||
use std::net::TcpStream;
|
use std::net::TcpStream;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
|
|
||||||
use crypto::hash::Type::{SHA256};
|
use crypto::hash::Type::SHA256;
|
||||||
use ssl::SslMethod;
|
use ssl::SslMethod;
|
||||||
use ssl::SslMethod::Dtlsv1;
|
use ssl::SslMethod::Dtlsv1;
|
||||||
use ssl::{SslContext, SslStream, VerifyCallback};
|
use ssl::{SslContext, SslStream, VerifyCallback};
|
||||||
use ssl::SSL_VERIFY_PEER;
|
use ssl::SSL_VERIFY_PEER;
|
||||||
use x509::{X509StoreContext};
|
use x509::X509StoreContext;
|
||||||
|
|
||||||
const PROTOCOL:SslMethod = Dtlsv1;
|
const PROTOCOL: SslMethod = Dtlsv1;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_new_ctx() {
|
fn test_new_ctx() {
|
||||||
|
|
@ -811,9 +826,8 @@ mod dtlsv1 {
|
||||||
fn test_read_dtlsv1() {
|
fn test_read_dtlsv1() {
|
||||||
let (_s, stream) = Server::new_dtlsv1(Some("hello"));
|
let (_s, stream) = Server::new_dtlsv1(Some("hello"));
|
||||||
|
|
||||||
let mut stream = SslStream::connect_generic(&SslContext::new(Dtlsv1).unwrap(),
|
let mut stream = SslStream::connect_generic(&SslContext::new(Dtlsv1).unwrap(), stream).unwrap();
|
||||||
stream).unwrap();
|
let mut buf = [0u8; 100];
|
||||||
let mut buf = [0u8;100];
|
|
||||||
assert!(stream.read(&mut buf).is_ok());
|
assert!(stream.read(&mut buf).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -821,21 +835,27 @@ fn test_read_dtlsv1() {
|
||||||
#[cfg(feature = "sslv2")]
|
#[cfg(feature = "sslv2")]
|
||||||
fn test_sslv2_connect_failure() {
|
fn test_sslv2_connect_failure() {
|
||||||
let (_s, tcp) = Server::new_tcp(&["-no_ssl2", "-www"]);
|
let (_s, tcp) = Server::new_tcp(&["-no_ssl2", "-www"]);
|
||||||
SslStream::connect_generic(&SslContext::new(Sslv2).unwrap(),
|
SslStream::connect_generic(&SslContext::new(Sslv2).unwrap(), tcp)
|
||||||
tcp).err().unwrap();
|
.err()
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn wait_io(stream: &NonblockingSslStream<TcpStream>,
|
fn wait_io(stream: &NonblockingSslStream<TcpStream>, read: bool, timeout_ms: u32) -> bool {
|
||||||
read: bool,
|
|
||||||
timeout_ms: u32) -> bool {
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut set: select::fd_set = mem::zeroed();
|
let mut set: select::fd_set = mem::zeroed();
|
||||||
select::fd_set(&mut set, stream.get_ref());
|
select::fd_set(&mut set, stream.get_ref());
|
||||||
|
|
||||||
let write = if read {0 as *mut _} else {&mut set as *mut _};
|
let write = if read {
|
||||||
let read = if !read {0 as *mut _} else {&mut set as *mut _};
|
0 as *mut _
|
||||||
select::select(stream.get_ref(), read, write, 0 as *mut _, timeout_ms)
|
} else {
|
||||||
.unwrap()
|
&mut set as *mut _
|
||||||
|
};
|
||||||
|
let read = if !read {
|
||||||
|
0 as *mut _
|
||||||
|
} else {
|
||||||
|
&mut set as *mut _
|
||||||
|
};
|
||||||
|
select::select(stream.get_ref(), read, write, 0 as *mut _, timeout_ms).unwrap()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -858,16 +878,16 @@ fn test_write_nonblocking() {
|
||||||
match result {
|
match result {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
break;
|
break;
|
||||||
},
|
}
|
||||||
Err(NonblockingSslError::WantRead) => {
|
Err(NonblockingSslError::WantRead) => {
|
||||||
assert!(wait_io(&stream, true, 1000));
|
assert!(wait_io(&stream, true, 1000));
|
||||||
},
|
}
|
||||||
Err(NonblockingSslError::WantWrite) => {
|
Err(NonblockingSslError::WantWrite) => {
|
||||||
assert!(wait_io(&stream, false, 1000));
|
assert!(wait_io(&stream, false, 1000));
|
||||||
},
|
}
|
||||||
Err(other) => {
|
Err(other) => {
|
||||||
panic!("Unexpected SSL Error: {:?}", other);
|
panic!("Unexpected SSL Error: {:?}", other);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -896,16 +916,16 @@ fn test_read_nonblocking() {
|
||||||
Ok(n) => {
|
Ok(n) => {
|
||||||
assert_eq!(n, 9);
|
assert_eq!(n, 9);
|
||||||
break;
|
break;
|
||||||
},
|
}
|
||||||
Err(NonblockingSslError::WantRead) => {
|
Err(NonblockingSslError::WantRead) => {
|
||||||
assert!(wait_io(&stream, true, 1000));
|
assert!(wait_io(&stream, true, 1000));
|
||||||
},
|
}
|
||||||
Err(NonblockingSslError::WantWrite) => {
|
Err(NonblockingSslError::WantWrite) => {
|
||||||
assert!(wait_io(&stream, false, 1000));
|
assert!(wait_io(&stream, false, 1000));
|
||||||
},
|
}
|
||||||
Err(other) => {
|
Err(other) => {
|
||||||
panic!("Unexpected SSL Error: {:?}", other);
|
panic!("Unexpected SSL Error: {:?}", other);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut input_buffer = [0u8; 1500];
|
let mut input_buffer = [0u8; 1500];
|
||||||
|
|
@ -916,15 +936,15 @@ fn test_read_nonblocking() {
|
||||||
// unlucky context switching, the response could actually
|
// unlucky context switching, the response could actually
|
||||||
// be in the receive buffer before we issue the read() syscall...
|
// be in the receive buffer before we issue the read() syscall...
|
||||||
n
|
n
|
||||||
},
|
}
|
||||||
Err(NonblockingSslError::WantRead) => {
|
Err(NonblockingSslError::WantRead) => {
|
||||||
assert!(wait_io(&stream, true, 3000));
|
assert!(wait_io(&stream, true, 3000));
|
||||||
// Second read should return application data.
|
// Second read should return application data.
|
||||||
stream.read(&mut input_buffer).unwrap()
|
stream.read(&mut input_buffer).unwrap()
|
||||||
},
|
}
|
||||||
Err(other) => {
|
Err(other) => {
|
||||||
panic!("Unexpected SSL Error: {:?}", other);
|
panic!("Unexpected SSL Error: {:?}", other);
|
||||||
},
|
}
|
||||||
};
|
};
|
||||||
assert!(bytes_read >= 5);
|
assert!(bytes_read >= 5);
|
||||||
assert_eq!(&input_buffer[..5], b"HTTP/");
|
assert_eq!(&input_buffer[..5], b"HTTP/");
|
||||||
|
|
|
||||||
|
|
@ -26,9 +26,9 @@ pub enum Extension {
|
||||||
/// The extended purposes of the key contained in the certificate
|
/// The extended purposes of the key contained in the certificate
|
||||||
ExtKeyUsage(Vec<ExtKeyUsageOption>),
|
ExtKeyUsage(Vec<ExtKeyUsageOption>),
|
||||||
/// Subject Alternative Names
|
/// Subject Alternative Names
|
||||||
SubjectAltName(Vec<(AltNameOption,String)>),
|
SubjectAltName(Vec<(AltNameOption, String)>),
|
||||||
/// Issuer Alternative Names
|
/// Issuer Alternative Names
|
||||||
IssuerAltName(Vec<(AltNameOption,String)>),
|
IssuerAltName(Vec<(AltNameOption, String)>),
|
||||||
/// Arbitrary extensions by NID. See `man x509v3_config` for value syntax.
|
/// Arbitrary extensions by NID. See `man x509v3_config` for value syntax.
|
||||||
///
|
///
|
||||||
/// You must not use this to add extensions which this enum can express directly.
|
/// You must not use this to add extensions which this enum can express directly.
|
||||||
|
|
@ -40,7 +40,7 @@ pub enum Extension {
|
||||||
/// # let generator = openssl::x509::X509Generator::new();
|
/// # let generator = openssl::x509::X509Generator::new();
|
||||||
/// generator.add_extension(OtherNid(Nid::BasicConstraints,"critical,CA:TRUE".to_owned()));
|
/// generator.add_extension(OtherNid(Nid::BasicConstraints,"critical,CA:TRUE".to_owned()));
|
||||||
/// ```
|
/// ```
|
||||||
OtherNid(Nid,String),
|
OtherNid(Nid, String),
|
||||||
/// Arbitrary extensions by OID string. See `man ASN1_generate_nconf` for value syntax.
|
/// Arbitrary extensions by OID string. See `man ASN1_generate_nconf` for value syntax.
|
||||||
///
|
///
|
||||||
/// You must not use this to add extensions which this enum can express directly.
|
/// You must not use this to add extensions which this enum can express directly.
|
||||||
|
|
@ -51,7 +51,7 @@ pub enum Extension {
|
||||||
/// # let generator = openssl::x509::X509Generator::new();
|
/// # let generator = openssl::x509::X509Generator::new();
|
||||||
/// generator.add_extension(OtherStr("2.999.2".to_owned(),"ASN1:UTF8:example value".to_owned()));
|
/// generator.add_extension(OtherStr("2.999.2".to_owned(),"ASN1:UTF8:example value".to_owned()));
|
||||||
/// ```
|
/// ```
|
||||||
OtherStr(String,String),
|
OtherStr(String, String),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Extension {
|
impl Extension {
|
||||||
|
|
@ -61,8 +61,8 @@ impl Extension {
|
||||||
&Extension::ExtKeyUsage(_) => ExtensionType::ExtKeyUsage,
|
&Extension::ExtKeyUsage(_) => ExtensionType::ExtKeyUsage,
|
||||||
&Extension::SubjectAltName(_) => ExtensionType::SubjectAltName,
|
&Extension::SubjectAltName(_) => ExtensionType::SubjectAltName,
|
||||||
&Extension::IssuerAltName(_) => ExtensionType::IssuerAltName,
|
&Extension::IssuerAltName(_) => ExtensionType::IssuerAltName,
|
||||||
&Extension::OtherNid(nid,_) => ExtensionType::OtherNid(nid),
|
&Extension::OtherNid(nid, _) => ExtensionType::OtherNid(nid),
|
||||||
&Extension::OtherStr(ref s,_) => ExtensionType::OtherStr(s.clone()),
|
&Extension::OtherStr(ref s, _) => ExtensionType::OtherStr(s.clone()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -89,9 +89,11 @@ impl ExtensionType {
|
||||||
|
|
||||||
// FIXME: This would be nicer as a method on Iterator<Item=ToString>. This can
|
// FIXME: This would be nicer as a method on Iterator<Item=ToString>. This can
|
||||||
// eventually be replaced by the successor to std::slice::SliceConcatExt.connect
|
// eventually be replaced by the successor to std::slice::SliceConcatExt.connect
|
||||||
fn join<I: Iterator<Item=T>,T: ToString>(iter: I, sep: &str) -> String {
|
fn join<I: Iterator<Item = T>, T: ToString>(iter: I, sep: &str) -> String {
|
||||||
iter.enumerate().fold(String::new(), |mut acc, (idx, v)| {
|
iter.enumerate().fold(String::new(), |mut acc, (idx, v)| {
|
||||||
if idx > 0 { acc.push_str(sep) };
|
if idx > 0 {
|
||||||
|
acc.push_str(sep)
|
||||||
|
};
|
||||||
acc.push_str(&v.to_string());
|
acc.push_str(&v.to_string());
|
||||||
acc
|
acc
|
||||||
})
|
})
|
||||||
|
|
@ -100,12 +102,18 @@ fn join<I: Iterator<Item=T>,T: ToString>(iter: I, sep: &str) -> String {
|
||||||
impl ToString for Extension {
|
impl ToString for Extension {
|
||||||
fn to_string(&self) -> String {
|
fn to_string(&self) -> String {
|
||||||
match self {
|
match self {
|
||||||
&Extension::KeyUsage(ref purposes) => join(purposes.iter(),","),
|
&Extension::KeyUsage(ref purposes) => join(purposes.iter(), ","),
|
||||||
&Extension::ExtKeyUsage(ref purposes) => join(purposes.iter(),","),
|
&Extension::ExtKeyUsage(ref purposes) => join(purposes.iter(), ","),
|
||||||
&Extension::SubjectAltName(ref names) => join(names.iter().map(|&(ref opt,ref val)|opt.to_string()+":"+&val),","),
|
&Extension::SubjectAltName(ref names) => {
|
||||||
&Extension::IssuerAltName(ref names) => join(names.iter().map(|&(ref opt,ref val)|opt.to_string()+":"+&val),","),
|
join(names.iter().map(|&(ref opt, ref val)| opt.to_string() + ":" + &val),
|
||||||
&Extension::OtherNid(_,ref value) => value.clone(),
|
",")
|
||||||
&Extension::OtherStr(_,ref value) => value.clone(),
|
}
|
||||||
|
&Extension::IssuerAltName(ref names) => {
|
||||||
|
join(names.iter().map(|&(ref opt, ref val)| opt.to_string() + ":" + &val),
|
||||||
|
",")
|
||||||
|
}
|
||||||
|
&Extension::OtherNid(_, ref value) => value.clone(),
|
||||||
|
&Extension::OtherStr(_, ref value) => value.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -169,7 +177,7 @@ impl fmt::Display for ExtKeyUsageOption {
|
||||||
&ExtKeyUsageOption::MsCtlSign => "msCTLSign",
|
&ExtKeyUsageOption::MsCtlSign => "msCTLSign",
|
||||||
&ExtKeyUsageOption::MsSgc => "msSGC",
|
&ExtKeyUsageOption::MsSgc => "msSGC",
|
||||||
&ExtKeyUsageOption::MsEfs => "msEFS",
|
&ExtKeyUsageOption::MsEfs => "msEFS",
|
||||||
&ExtKeyUsageOption::NsSgc =>"nsSGC",
|
&ExtKeyUsageOption::NsSgc => "nsSGC",
|
||||||
&ExtKeyUsageOption::Other(ref s) => &s[..],
|
&ExtKeyUsageOption::Other(ref s) => &s[..],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -189,9 +197,9 @@ pub enum AltNameOption {
|
||||||
Other,
|
Other,
|
||||||
Email,
|
Email,
|
||||||
DNS,
|
DNS,
|
||||||
//X400, // Not supported by OpenSSL
|
// X400, // Not supported by OpenSSL
|
||||||
Directory,
|
Directory,
|
||||||
//EDIParty, // Not supported by OpenSSL
|
// EDIParty, // Not supported by OpenSSL
|
||||||
URI,
|
URI,
|
||||||
IPAddress,
|
IPAddress,
|
||||||
RegisteredID,
|
RegisteredID,
|
||||||
|
|
|
||||||
|
|
@ -11,11 +11,11 @@ use std::fmt;
|
||||||
use std::str;
|
use std::str;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use asn1::{Asn1Time};
|
use asn1::Asn1Time;
|
||||||
use bio::{MemBio};
|
use bio::MemBio;
|
||||||
use crypto::hash;
|
use crypto::hash;
|
||||||
use crypto::hash::Type as HashType;
|
use crypto::hash::Type as HashType;
|
||||||
use crypto::pkey::{PKey,Parts};
|
use crypto::pkey::{PKey, Parts};
|
||||||
use crypto::rand::rand_bytes;
|
use crypto::rand::rand_bytes;
|
||||||
use ffi;
|
use ffi;
|
||||||
use ffi_extras;
|
use ffi_extras;
|
||||||
|
|
@ -24,18 +24,20 @@ use nid;
|
||||||
|
|
||||||
pub mod extension;
|
pub mod extension;
|
||||||
|
|
||||||
use self::extension::{ExtensionType,Extension};
|
use self::extension::{ExtensionType, Extension};
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|
||||||
pub struct SslString {
|
pub struct SslString {
|
||||||
s : &'static str
|
s: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'s> Drop for SslString {
|
impl<'s> Drop for SslString {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
unsafe { ffi::CRYPTO_free(self.s.as_ptr() as *mut c_void); }
|
unsafe {
|
||||||
|
ffi::CRYPTO_free(self.s.as_ptr() as *mut c_void);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -49,9 +51,7 @@ impl Deref for SslString {
|
||||||
|
|
||||||
impl SslString {
|
impl SslString {
|
||||||
unsafe fn new(buf: *const c_char) -> SslString {
|
unsafe fn new(buf: *const c_char) -> SslString {
|
||||||
SslString {
|
SslString { s: str::from_utf8(CStr::from_ptr(buf as *const _).to_bytes()).unwrap() }
|
||||||
s: str::from_utf8(CStr::from_ptr(buf as *const _).to_bytes()).unwrap()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -72,19 +72,17 @@ impl fmt::Debug for SslString {
|
||||||
pub enum X509FileType {
|
pub enum X509FileType {
|
||||||
PEM = ffi::X509_FILETYPE_PEM,
|
PEM = ffi::X509_FILETYPE_PEM,
|
||||||
ASN1 = ffi::X509_FILETYPE_ASN1,
|
ASN1 = ffi::X509_FILETYPE_ASN1,
|
||||||
Default = ffi::X509_FILETYPE_DEFAULT
|
Default = ffi::X509_FILETYPE_DEFAULT,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(missing_copy_implementations)]
|
#[allow(missing_copy_implementations)]
|
||||||
pub struct X509StoreContext {
|
pub struct X509StoreContext {
|
||||||
ctx: *mut ffi::X509_STORE_CTX
|
ctx: *mut ffi::X509_STORE_CTX,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl X509StoreContext {
|
impl X509StoreContext {
|
||||||
pub fn new(ctx: *mut ffi::X509_STORE_CTX) -> X509StoreContext {
|
pub fn new(ctx: *mut ffi::X509_STORE_CTX) -> X509StoreContext {
|
||||||
X509StoreContext {
|
X509StoreContext { ctx: ctx }
|
||||||
ctx: ctx
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_error(&self) -> Option<X509ValidationError> {
|
pub fn get_error(&self) -> Option<X509ValidationError> {
|
||||||
|
|
@ -98,7 +96,11 @@ impl X509StoreContext {
|
||||||
if ptr.is_null() {
|
if ptr.is_null() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some(X509 { ctx: Some(self), handle: ptr, owned: false })
|
Some(X509 {
|
||||||
|
ctx: Some(self),
|
||||||
|
handle: ptr,
|
||||||
|
owned: false,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -143,9 +145,9 @@ impl X509StoreContext {
|
||||||
pub struct X509Generator {
|
pub struct X509Generator {
|
||||||
bits: u32,
|
bits: u32,
|
||||||
days: u32,
|
days: u32,
|
||||||
names: Vec<(String,String)>,
|
names: Vec<(String, String)>,
|
||||||
// RFC 3280 §4.2: A certificate MUST NOT include more than one instance of a particular extension.
|
// RFC 3280 §4.2: A certificate MUST NOT include more than one instance of a particular extension.
|
||||||
extensions: HashMap<ExtensionType,Extension>,
|
extensions: HashMap<ExtensionType, Extension>,
|
||||||
hash_type: HashType,
|
hash_type: HashType,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -165,7 +167,7 @@ impl X509Generator {
|
||||||
days: 365,
|
days: 365,
|
||||||
names: vec![],
|
names: vec![],
|
||||||
extensions: HashMap::new(),
|
extensions: HashMap::new(),
|
||||||
hash_type: HashType::SHA1
|
hash_type: HashType::SHA1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -188,7 +190,7 @@ impl X509Generator {
|
||||||
/// generator.add_name("CN".to_string(),"example.com".to_string());
|
/// generator.add_name("CN".to_string(),"example.com".to_string());
|
||||||
/// ```
|
/// ```
|
||||||
pub fn add_name(mut self, attr_type: String, attr_value: String) -> X509Generator {
|
pub fn add_name(mut self, attr_type: String, attr_value: String) -> X509Generator {
|
||||||
self.names.push((attr_type,attr_value));
|
self.names.push((attr_type, attr_value));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -199,7 +201,8 @@ impl X509Generator {
|
||||||
/// generator.add_names(vec![("CN".to_string(),"example.com".to_string())]);
|
/// generator.add_names(vec![("CN".to_string(),"example.com".to_string())]);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn add_names<I>(mut self, attrs: I) -> X509Generator
|
pub fn add_names<I>(mut self, attrs: I) -> X509Generator
|
||||||
where I: IntoIterator<Item=(String,String)> {
|
where I: IntoIterator<Item = (String, String)>
|
||||||
|
{
|
||||||
self.names.extend(attrs);
|
self.names.extend(attrs);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
@ -216,7 +219,7 @@ impl X509Generator {
|
||||||
/// generator.add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment]));
|
/// generator.add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment]));
|
||||||
/// ```
|
/// ```
|
||||||
pub fn add_extension(mut self, ext: extension::Extension) -> X509Generator {
|
pub fn add_extension(mut self, ext: extension::Extension) -> X509Generator {
|
||||||
self.extensions.insert(ext.get_type(),ext);
|
self.extensions.insert(ext.get_type(), ext);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -232,8 +235,9 @@ impl X509Generator {
|
||||||
/// generator.add_extensions(vec![KeyUsage(vec![DigitalSignature, KeyEncipherment])]);
|
/// generator.add_extensions(vec![KeyUsage(vec![DigitalSignature, KeyEncipherment])]);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn add_extensions<I>(mut self, exts: I) -> X509Generator
|
pub fn add_extensions<I>(mut self, exts: I) -> X509Generator
|
||||||
where I: IntoIterator<Item=extension::Extension> {
|
where I: IntoIterator<Item = extension::Extension>
|
||||||
self.extensions.extend(exts.into_iter().map(|ext|(ext.get_type(),ext)));
|
{
|
||||||
|
self.extensions.extend(exts.into_iter().map(|ext| (ext.get_type(), ext)));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -242,23 +246,27 @@ impl X509Generator {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_extension_internal(x509: *mut ffi::X509, exttype: &extension::ExtensionType, value: &str) -> Result<(), SslError> {
|
fn add_extension_internal(x509: *mut ffi::X509,
|
||||||
|
exttype: &extension::ExtensionType,
|
||||||
|
value: &str)
|
||||||
|
-> Result<(), SslError> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut ctx: ffi::X509V3_CTX = mem::zeroed();
|
let mut ctx: ffi::X509V3_CTX = mem::zeroed();
|
||||||
ffi::X509V3_set_ctx(&mut ctx, x509, x509,
|
ffi::X509V3_set_ctx(&mut ctx, x509, x509, ptr::null_mut(), ptr::null_mut(), 0);
|
||||||
ptr::null_mut(), ptr::null_mut(), 0);
|
|
||||||
let value = CString::new(value.as_bytes()).unwrap();
|
let value = CString::new(value.as_bytes()).unwrap();
|
||||||
let ext=match exttype.get_nid() {
|
let ext = match exttype.get_nid() {
|
||||||
Some(nid) => ffi::X509V3_EXT_conf_nid(ptr::null_mut(),
|
Some(nid) => {
|
||||||
mem::transmute(&ctx),
|
ffi::X509V3_EXT_conf_nid(ptr::null_mut(),
|
||||||
nid as c_int,
|
mem::transmute(&ctx),
|
||||||
value.as_ptr() as *mut c_char),
|
nid as c_int,
|
||||||
|
value.as_ptr() as *mut c_char)
|
||||||
|
}
|
||||||
None => {
|
None => {
|
||||||
let name=CString::new(exttype.get_name().unwrap().as_bytes()).unwrap();
|
let name = CString::new(exttype.get_name().unwrap().as_bytes()).unwrap();
|
||||||
ffi::X509V3_EXT_conf(ptr::null_mut(),
|
ffi::X509V3_EXT_conf(ptr::null_mut(),
|
||||||
mem::transmute(&ctx),
|
mem::transmute(&ctx),
|
||||||
name.as_ptr() as *mut c_char,
|
name.as_ptr() as *mut c_char,
|
||||||
value.as_ptr() as *mut c_char)
|
value.as_ptr() as *mut c_char)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let mut success = false;
|
let mut success = false;
|
||||||
|
|
@ -270,13 +278,21 @@ impl X509Generator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_name_internal(name: *mut ffi::X509_NAME, key: &str, value: &str) -> Result<(), SslError> {
|
fn add_name_internal(name: *mut ffi::X509_NAME,
|
||||||
|
key: &str,
|
||||||
|
value: &str)
|
||||||
|
-> Result<(), SslError> {
|
||||||
let value_len = value.len() as c_int;
|
let value_len = value.len() as c_int;
|
||||||
lift_ssl!(unsafe {
|
lift_ssl!(unsafe {
|
||||||
let key = CString::new(key.as_bytes()).unwrap();
|
let key = CString::new(key.as_bytes()).unwrap();
|
||||||
let value = CString::new(value.as_bytes()).unwrap();
|
let value = CString::new(value.as_bytes()).unwrap();
|
||||||
ffi::X509_NAME_add_entry_by_txt(name, key.as_ptr() as *const _, ffi::MBSTRING_UTF8,
|
ffi::X509_NAME_add_entry_by_txt(name,
|
||||||
value.as_ptr() as *const _, value_len, -1, 0)
|
key.as_ptr() as *const _,
|
||||||
|
ffi::MBSTRING_UTF8,
|
||||||
|
value.as_ptr() as *const _,
|
||||||
|
value_len,
|
||||||
|
-1,
|
||||||
|
0)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -315,10 +331,15 @@ impl X509Generator {
|
||||||
let x509 = ffi::X509_new();
|
let x509 = ffi::X509_new();
|
||||||
try_ssl_null!(x509);
|
try_ssl_null!(x509);
|
||||||
|
|
||||||
let x509 = X509 { handle: x509, ctx: None, owned: true};
|
let x509 = X509 {
|
||||||
|
handle: x509,
|
||||||
|
ctx: None,
|
||||||
|
owned: true,
|
||||||
|
};
|
||||||
|
|
||||||
try_ssl!(ffi::X509_set_version(x509.handle, 2));
|
try_ssl!(ffi::X509_set_version(x509.handle, 2));
|
||||||
try_ssl!(ffi::ASN1_INTEGER_set(ffi::X509_get_serialNumber(x509.handle), X509Generator::random_serial()));
|
try_ssl!(ffi::ASN1_INTEGER_set(ffi::X509_get_serialNumber(x509.handle),
|
||||||
|
X509Generator::random_serial()));
|
||||||
|
|
||||||
let not_before = try!(Asn1Time::days_from_now(0));
|
let not_before = try!(Asn1Time::days_from_now(0));
|
||||||
let not_after = try!(Asn1Time::days_from_now(self.days));
|
let not_after = try!(Asn1Time::days_from_now(self.days));
|
||||||
|
|
@ -336,18 +357,21 @@ impl X509Generator {
|
||||||
let name = ffi::X509_get_subject_name(x509.handle);
|
let name = ffi::X509_get_subject_name(x509.handle);
|
||||||
try_ssl_null!(name);
|
try_ssl_null!(name);
|
||||||
|
|
||||||
let default=[("CN","rust-openssl")];
|
let default = [("CN", "rust-openssl")];
|
||||||
let default_iter=&mut default.iter().map(|&(k,v)|(k,v));
|
let default_iter = &mut default.iter().map(|&(k, v)| (k, v));
|
||||||
let arg_iter=&mut self.names.iter().map(|&(ref k,ref v)|(&k[..],&v[..]));
|
let arg_iter = &mut self.names.iter().map(|&(ref k, ref v)| (&k[..], &v[..]));
|
||||||
let iter: &mut Iterator<Item=(&str,&str)> =
|
let iter: &mut Iterator<Item = (&str, &str)> = if self.names.len() == 0 {
|
||||||
if self.names.len()==0 { default_iter } else { arg_iter };
|
default_iter
|
||||||
|
} else {
|
||||||
|
arg_iter
|
||||||
|
};
|
||||||
|
|
||||||
for (key,val) in iter {
|
for (key, val) in iter {
|
||||||
try!(X509Generator::add_name_internal(name, &key, &val));
|
try!(X509Generator::add_name_internal(name, &key, &val));
|
||||||
}
|
}
|
||||||
ffi::X509_set_issuer_name(x509.handle, name);
|
ffi::X509_set_issuer_name(x509.handle, name);
|
||||||
|
|
||||||
for (exttype,ext) in self.extensions.iter() {
|
for (exttype, ext) in self.extensions.iter() {
|
||||||
try!(X509Generator::add_extension_internal(x509.handle, exttype, &ext.to_string()));
|
try!(X509Generator::add_extension_internal(x509.handle, exttype, &ext.to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -359,9 +383,9 @@ impl X509Generator {
|
||||||
|
|
||||||
/// Obtain a certificate signing request (CSR)
|
/// Obtain a certificate signing request (CSR)
|
||||||
pub fn request(&self, p_key: &PKey) -> Result<X509Req, SslError> {
|
pub fn request(&self, p_key: &PKey) -> Result<X509Req, SslError> {
|
||||||
let cert=match self.sign(p_key) {
|
let cert = match self.sign(p_key) {
|
||||||
Ok(c) => c,
|
Ok(c) => c,
|
||||||
Err(x) => return Err(x)
|
Err(x) => return Err(x),
|
||||||
};
|
};
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
|
|
@ -370,7 +394,7 @@ impl X509Generator {
|
||||||
|
|
||||||
let exts = ffi_extras::X509_get_extensions(cert.handle);
|
let exts = ffi_extras::X509_get_extensions(cert.handle);
|
||||||
if exts != ptr::null_mut() {
|
if exts != ptr::null_mut() {
|
||||||
try_ssl!(ffi::X509_REQ_add_extensions(req,exts));
|
try_ssl!(ffi::X509_REQ_add_extensions(req, exts));
|
||||||
}
|
}
|
||||||
|
|
||||||
let hash_fn = self.hash_type.evp_md();
|
let hash_fn = self.hash_type.evp_md();
|
||||||
|
|
@ -387,7 +411,7 @@ impl X509Generator {
|
||||||
pub struct X509<'ctx> {
|
pub struct X509<'ctx> {
|
||||||
ctx: Option<&'ctx X509StoreContext>,
|
ctx: Option<&'ctx X509StoreContext>,
|
||||||
handle: *mut ffi::X509,
|
handle: *mut ffi::X509,
|
||||||
owned: bool
|
owned: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'ctx> X509<'ctx> {
|
impl<'ctx> X509<'ctx> {
|
||||||
|
|
@ -406,19 +430,22 @@ impl<'ctx> X509<'ctx> {
|
||||||
X509 {
|
X509 {
|
||||||
ctx: Some(ctx),
|
ctx: Some(ctx),
|
||||||
handle: handle,
|
handle: handle,
|
||||||
owned: false
|
owned: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads certificate from PEM, takes ownership of handle
|
/// Reads certificate from PEM, takes ownership of handle
|
||||||
pub fn from_pem<R>(reader: &mut R) -> Result<X509<'ctx>, SslError> where R: Read {
|
pub fn from_pem<R>(reader: &mut R) -> Result<X509<'ctx>, SslError>
|
||||||
|
where R: Read
|
||||||
|
{
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let handle = try_ssl_null!(ffi::PEM_read_bio_X509(mem_bio.get_handle(),
|
let handle = try_ssl_null!(ffi::PEM_read_bio_X509(mem_bio.get_handle(),
|
||||||
ptr::null_mut(),
|
ptr::null_mut(),
|
||||||
None, ptr::null_mut()));
|
None,
|
||||||
|
ptr::null_mut()));
|
||||||
Ok(X509::new(handle, true))
|
Ok(X509::new(handle, true))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -429,7 +456,10 @@ impl<'ctx> X509<'ctx> {
|
||||||
|
|
||||||
pub fn subject_name<'a>(&'a self) -> X509Name<'a> {
|
pub fn subject_name<'a>(&'a self) -> X509Name<'a> {
|
||||||
let name = unsafe { ffi::X509_get_subject_name(self.handle) };
|
let name = unsafe { ffi::X509_get_subject_name(self.handle) };
|
||||||
X509Name { x509: self, name: name }
|
X509Name {
|
||||||
|
x509: self,
|
||||||
|
name: name,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn public_key(&self) -> PKey {
|
pub fn public_key(&self) -> PKey {
|
||||||
|
|
@ -446,7 +476,9 @@ impl<'ctx> X509<'ctx> {
|
||||||
let v: Vec<u8> = repeat(0).take(len as usize).collect();
|
let v: Vec<u8> = repeat(0).take(len as usize).collect();
|
||||||
let act_len: c_uint = 0;
|
let act_len: c_uint = 0;
|
||||||
let res = unsafe {
|
let res = unsafe {
|
||||||
ffi::X509_digest(self.handle, evp, mem::transmute(v.as_ptr()),
|
ffi::X509_digest(self.handle,
|
||||||
|
evp,
|
||||||
|
mem::transmute(v.as_ptr()),
|
||||||
mem::transmute(&act_len))
|
mem::transmute(&act_len))
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -457,18 +489,19 @@ impl<'ctx> X509<'ctx> {
|
||||||
match len.cmp(&act_len) {
|
match len.cmp(&act_len) {
|
||||||
Ordering::Greater => None,
|
Ordering::Greater => None,
|
||||||
Ordering::Equal => Some(v),
|
Ordering::Equal => Some(v),
|
||||||
Ordering::Less => panic!("Fingerprint buffer was corrupted!")
|
Ordering::Less => panic!("Fingerprint buffer was corrupted!"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes certificate as PEM
|
/// Writes certificate as PEM
|
||||||
pub fn write_pem<W>(&self, writer: &mut W) -> Result<(), SslError> where W: Write {
|
pub fn write_pem<W>(&self, writer: &mut W) -> Result<(), SslError>
|
||||||
|
where W: Write
|
||||||
|
{
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
unsafe {
|
unsafe {
|
||||||
try_ssl!(ffi::PEM_write_bio_X509(mem_bio.get_handle(),
|
try_ssl!(ffi::PEM_write_bio_X509(mem_bio.get_handle(), self.handle));
|
||||||
self.handle));
|
|
||||||
}
|
}
|
||||||
io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ())
|
io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
@ -485,16 +518,16 @@ impl<'ctx> Drop for X509<'ctx> {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct X509Name<'x> {
|
pub struct X509Name<'x> {
|
||||||
x509: &'x X509<'x>,
|
x509: &'x X509<'x>,
|
||||||
name: *mut ffi::X509_NAME
|
name: *mut ffi::X509_NAME,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct X509NameEntry<'x> {
|
pub struct X509NameEntry<'x> {
|
||||||
x509_name: &'x X509Name<'x>,
|
x509_name: &'x X509Name<'x>,
|
||||||
ne: *mut ffi::X509_NAME_ENTRY
|
ne: *mut ffi::X509_NAME_ENTRY,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl <'x> X509Name<'x> {
|
impl<'x> X509Name<'x> {
|
||||||
pub fn text_by_nid(&self, nid: nid::Nid) -> Option<SslString> {
|
pub fn text_by_nid(&self, nid: nid::Nid) -> Option<SslString> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let loc = ffi::X509_NAME_get_index_by_NID(self.name, nid as c_int, -1);
|
let loc = ffi::X509_NAME_get_index_by_NID(self.name, nid as c_int, -1);
|
||||||
|
|
@ -512,11 +545,11 @@ impl <'x> X509Name<'x> {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut str_from_asn1 : *mut c_char = ptr::null_mut();
|
let mut str_from_asn1: *mut c_char = ptr::null_mut();
|
||||||
let len = ffi::ASN1_STRING_to_UTF8(&mut str_from_asn1, asn1_str);
|
let len = ffi::ASN1_STRING_to_UTF8(&mut str_from_asn1, asn1_str);
|
||||||
|
|
||||||
if len < 0 {
|
if len < 0 {
|
||||||
return None
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
assert!(!str_from_asn1.is_null());
|
assert!(!str_from_asn1.is_null());
|
||||||
|
|
@ -534,30 +567,32 @@ pub struct X509Req {
|
||||||
impl X509Req {
|
impl X509Req {
|
||||||
/// Creates new from handle
|
/// Creates new from handle
|
||||||
pub fn new(handle: *mut ffi::X509_REQ) -> X509Req {
|
pub fn new(handle: *mut ffi::X509_REQ) -> X509Req {
|
||||||
X509Req {
|
X509Req { handle: handle }
|
||||||
handle: handle,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads CSR from PEM
|
/// Reads CSR from PEM
|
||||||
pub fn from_pem<R>(reader: &mut R) -> Result<X509Req, SslError> where R: Read {
|
pub fn from_pem<R>(reader: &mut R) -> Result<X509Req, SslError>
|
||||||
|
where R: Read
|
||||||
|
{
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
try!(io::copy(reader, &mut mem_bio).map_err(StreamError));
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let handle = try_ssl_null!(ffi::PEM_read_bio_X509_REQ(mem_bio.get_handle(),
|
let handle = try_ssl_null!(ffi::PEM_read_bio_X509_REQ(mem_bio.get_handle(),
|
||||||
ptr::null_mut(),
|
ptr::null_mut(),
|
||||||
None, ptr::null_mut()));
|
None,
|
||||||
|
ptr::null_mut()));
|
||||||
Ok(X509Req::new(handle))
|
Ok(X509Req::new(handle))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes CSR as PEM
|
/// Writes CSR as PEM
|
||||||
pub fn write_pem<W>(&self, writer: &mut W) -> Result<(), SslError> where W: Write {
|
pub fn write_pem<W>(&self, writer: &mut W) -> Result<(), SslError>
|
||||||
|
where W: Write
|
||||||
|
{
|
||||||
let mut mem_bio = try!(MemBio::new());
|
let mut mem_bio = try!(MemBio::new());
|
||||||
unsafe {
|
unsafe {
|
||||||
try_ssl!(ffi::PEM_write_bio_X509_REQ(mem_bio.get_handle(),
|
try_ssl!(ffi::PEM_write_bio_X509_REQ(mem_bio.get_handle(), self.handle));
|
||||||
self.handle));
|
|
||||||
}
|
}
|
||||||
io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ())
|
io::copy(&mut mem_bio, writer).map_err(StreamError).map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
@ -651,6 +686,7 @@ make_validation_error!(X509_V_OK,
|
||||||
fn test_negative_serial() {
|
fn test_negative_serial() {
|
||||||
// I guess that's enough to get a random negative number
|
// I guess that's enough to get a random negative number
|
||||||
for _ in 0..1000 {
|
for _ in 0..1000 {
|
||||||
assert!(X509Generator::random_serial() > 0, "All serials should be positive");
|
assert!(X509Generator::random_serial() > 0,
|
||||||
|
"All serials should be positive");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,10 +3,10 @@ use std::io;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
|
|
||||||
use crypto::hash::Type::{SHA256};
|
use crypto::hash::Type::SHA256;
|
||||||
use crypto::pkey::PKey;
|
use crypto::pkey::PKey;
|
||||||
use x509::{X509, X509Generator};
|
use x509::{X509, X509Generator};
|
||||||
use x509::extension::Extension::{KeyUsage,ExtKeyUsage,SubjectAltName,OtherNid,OtherStr};
|
use x509::extension::Extension::{KeyUsage, ExtKeyUsage, SubjectAltName, OtherNid, OtherStr};
|
||||||
use x509::extension::AltNameOption as SAN;
|
use x509::extension::AltNameOption as SAN;
|
||||||
use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment};
|
use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment};
|
||||||
use x509::extension::ExtKeyUsageOption::{self, ClientAuth, ServerAuth};
|
use x509::extension::ExtKeyUsageOption::{self, ClientAuth, ServerAuth};
|
||||||
|
|
@ -15,14 +15,16 @@ use nid::Nid;
|
||||||
fn get_generator() -> X509Generator {
|
fn get_generator() -> X509Generator {
|
||||||
X509Generator::new()
|
X509Generator::new()
|
||||||
.set_bitlength(2048)
|
.set_bitlength(2048)
|
||||||
.set_valid_period(365*2)
|
.set_valid_period(365 * 2)
|
||||||
.add_name("CN".to_string(),"test_me".to_string())
|
.add_name("CN".to_string(), "test_me".to_string())
|
||||||
.set_sign_hash(SHA256)
|
.set_sign_hash(SHA256)
|
||||||
.add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment]))
|
.add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment]))
|
||||||
.add_extension(ExtKeyUsage(vec![ClientAuth, ServerAuth, ExtKeyUsageOption::Other("2.999.1".to_owned())]))
|
.add_extension(ExtKeyUsage(vec![ClientAuth,
|
||||||
.add_extension(SubjectAltName(vec![(SAN::DNS,"example.com".to_owned())]))
|
ServerAuth,
|
||||||
.add_extension(OtherNid(Nid::BasicConstraints,"critical,CA:TRUE".to_owned()))
|
ExtKeyUsageOption::Other("2.999.1".to_owned())]))
|
||||||
.add_extension(OtherStr("2.999.2".to_owned(),"ASN1:UTF8:example value".to_owned()))
|
.add_extension(SubjectAltName(vec![(SAN::DNS, "example.com".to_owned())]))
|
||||||
|
.add_extension(OtherNid(Nid::BasicConstraints, "critical,CA:TRUE".to_owned()))
|
||||||
|
.add_extension(OtherStr("2.999.2".to_owned(), "ASN1:UTF8:example value".to_owned()))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -53,8 +55,8 @@ fn test_req_gen() {
|
||||||
fn test_cert_loading() {
|
fn test_cert_loading() {
|
||||||
let cert_path = Path::new("test/cert.pem");
|
let cert_path = Path::new("test/cert.pem");
|
||||||
let mut file = File::open(&cert_path)
|
let mut file = File::open(&cert_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/cert.pem`");
|
.expect("Failed to open `test/cert.pem`");
|
||||||
|
|
||||||
let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM");
|
let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM");
|
||||||
let fingerprint = cert.fingerprint(SHA256).unwrap();
|
let fingerprint = cert.fingerprint(SHA256).unwrap();
|
||||||
|
|
@ -73,14 +75,14 @@ fn test_cert_loading() {
|
||||||
fn test_subject_read_cn() {
|
fn test_subject_read_cn() {
|
||||||
let cert_path = Path::new("test/cert.pem");
|
let cert_path = Path::new("test/cert.pem");
|
||||||
let mut file = File::open(&cert_path)
|
let mut file = File::open(&cert_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/cert.pem`");
|
.expect("Failed to open `test/cert.pem`");
|
||||||
|
|
||||||
let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM");
|
let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM");
|
||||||
let subject = cert.subject_name();
|
let subject = cert.subject_name();
|
||||||
let cn = match subject.text_by_nid(Nid::CN) {
|
let cn = match subject.text_by_nid(Nid::CN) {
|
||||||
Some(x) => x,
|
Some(x) => x,
|
||||||
None => panic!("Failed to read CN from cert")
|
None => panic!("Failed to read CN from cert"),
|
||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(&cn as &str, "test_cert")
|
assert_eq!(&cn as &str, "test_cert")
|
||||||
|
|
@ -90,27 +92,27 @@ fn test_subject_read_cn() {
|
||||||
fn test_nid_values() {
|
fn test_nid_values() {
|
||||||
let cert_path = Path::new("test/nid_test_cert.pem");
|
let cert_path = Path::new("test/nid_test_cert.pem");
|
||||||
let mut file = File::open(&cert_path)
|
let mut file = File::open(&cert_path)
|
||||||
.ok()
|
.ok()
|
||||||
.expect("Failed to open `test/nid_test_cert.pem`");
|
.expect("Failed to open `test/nid_test_cert.pem`");
|
||||||
|
|
||||||
let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM");
|
let cert = X509::from_pem(&mut file).ok().expect("Failed to load PEM");
|
||||||
let subject = cert.subject_name();
|
let subject = cert.subject_name();
|
||||||
|
|
||||||
let cn = match subject.text_by_nid(Nid::CN) {
|
let cn = match subject.text_by_nid(Nid::CN) {
|
||||||
Some(x) => x,
|
Some(x) => x,
|
||||||
None => panic!("Failed to read CN from cert")
|
None => panic!("Failed to read CN from cert"),
|
||||||
};
|
};
|
||||||
assert_eq!(&cn as &str, "example.com");
|
assert_eq!(&cn as &str, "example.com");
|
||||||
|
|
||||||
let email = match subject.text_by_nid(Nid::Email) {
|
let email = match subject.text_by_nid(Nid::Email) {
|
||||||
Some(x) => x,
|
Some(x) => x,
|
||||||
None => panic!("Failed to read subject email address from cert")
|
None => panic!("Failed to read subject email address from cert"),
|
||||||
};
|
};
|
||||||
assert_eq!(&email as &str, "test@example.com");
|
assert_eq!(&email as &str, "test@example.com");
|
||||||
|
|
||||||
let friendly = match subject.text_by_nid(Nid::FriendlyName) {
|
let friendly = match subject.text_by_nid(Nid::FriendlyName) {
|
||||||
Some(x) => x,
|
Some(x) => x,
|
||||||
None => panic!("Failed to read subject friendly name from cert")
|
None => panic!("Failed to read subject friendly name from cert"),
|
||||||
};
|
};
|
||||||
assert_eq!(&friendly as &str, "Example");
|
assert_eq!(&friendly as &str, "Example");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,21 @@
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
|
if [ "$TRAVIS_OS_NAME" == "osx" ]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$TARGET" == "arm-unknown-linux-gnueabihf" ]; then
|
||||||
|
export C_INCLUDE_PATH=/usr/arm-linux-gnueabihf/include
|
||||||
|
CROSS=arm-linux-gnueabihf-
|
||||||
|
OS_COMPILER=linux-armv4
|
||||||
|
else
|
||||||
|
OS_COMPILER=linux-x86_64
|
||||||
|
fi
|
||||||
|
|
||||||
mkdir /tmp/openssl
|
mkdir /tmp/openssl
|
||||||
cd /tmp/openssl
|
cd /tmp/openssl
|
||||||
curl https://openssl.org/source/openssl-1.0.2e.tar.gz | tar --strip-components=1 -xzf -
|
curl https://openssl.org/source/openssl-1.0.2e.tar.gz | tar --strip-components=1 -xzf -
|
||||||
./config --prefix=$HOME/openssl shared
|
./Configure --prefix=$HOME/openssl shared --cross-compile-prefix=$CROSS $OS_COMPILER
|
||||||
make
|
make
|
||||||
make install
|
make install
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,32 @@
|
||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
MAIN_TARGETS=https://static.rust-lang.org/dist
|
||||||
|
|
||||||
|
if [ "$TEST_FEATURES" == "true" ]; then
|
||||||
|
FEATURES="tlsv1_2 tlsv1_1 dtlsv1 dtlsv1_2 sslv2 sslv3 aes_xts aes_ctr npn alpn rfc5114 ecdh_auto pkcs5_pbkdf2_hmac"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$TRAVIS_OS_NAME" != "osx" ]; then
|
||||||
|
export OPENSSL_LIB_DIR=$HOME/openssl/lib
|
||||||
|
export OPENSSL_INCLUDE_DIR=$HOME/openssl/include
|
||||||
|
export LD_LIBRARY_PATH=$HOME/openssl/lib:$LD_LIBRARY_PATH
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$TARGET" ]; then
|
||||||
|
FLAGS="--target=$TARGET"
|
||||||
|
COMMAND="build"
|
||||||
|
|
||||||
|
# Download the rustlib folder from the relevant portion of main distribution's
|
||||||
|
# tarballs.
|
||||||
|
dir=rust-std-$TARGET
|
||||||
|
pkg=rust-std
|
||||||
|
curl -s $MAIN_TARGETS/$pkg-$TRAVIS_RUST_VERSION-$TARGET.tar.gz | \
|
||||||
|
tar xzf - -C $HOME/rust/lib/rustlib --strip-components=4 \
|
||||||
|
$pkg-$TRAVIS_RUST_VERSION-$TARGET/$dir/lib/rustlib/$TARGET
|
||||||
|
else
|
||||||
|
COMMAND="test"
|
||||||
|
fi
|
||||||
|
|
||||||
|
export PATH=$HOME/openssl/bin:$PATH
|
||||||
|
(cd openssl && cargo $COMMAND $FLAGS --features "$FEATURES")
|
||||||
Loading…
Reference in New Issue