Merge pull request #141 from gkoz/borrow_mut
Improve Hasher and HMAC APIs
This commit is contained in:
commit
8b47daae66
|
|
@ -370,6 +370,7 @@ extern "C" {
|
|||
pub fn EVP_DigestFinal_ex(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int;
|
||||
|
||||
pub fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX;
|
||||
pub fn EVP_MD_CTX_copy_ex(dst: *mut EVP_MD_CTX, src: *const EVP_MD_CTX) -> c_int;
|
||||
pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX);
|
||||
|
||||
pub fn EVP_PKEY_new() -> *mut EVP_PKEY;
|
||||
|
|
@ -383,6 +384,7 @@ extern "C" {
|
|||
pub fn HMAC_Final(ctx: *mut HMAC_CTX, output: *mut u8, len: *mut c_uint) -> c_int;
|
||||
pub fn HMAC_Update(ctx: *mut HMAC_CTX, input: *const u8, len: c_uint) -> c_int;
|
||||
pub fn HMAC_CTX_cleanup(ctx: *mut HMAC_CTX);
|
||||
pub fn HMAC_CTX_copy(dst: *mut HMAC_CTX, src: *const HMAC_CTX) -> c_int;
|
||||
|
||||
|
||||
pub fn PEM_read_bio_X509(bio: *mut BIO, out: *mut *mut X509, callback: Option<PasswordCallback>,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
use libc::c_uint;
|
||||
use std::ptr;
|
||||
use std::old_io;
|
||||
use std::iter::repeat;
|
||||
use std::old_io::{IoError, Writer};
|
||||
|
||||
use ffi;
|
||||
|
||||
/// Message digest (hash) type.
|
||||
#[derive(Copy)]
|
||||
pub enum HashType {
|
||||
pub enum Type {
|
||||
MD5,
|
||||
SHA1,
|
||||
SHA224,
|
||||
|
|
@ -16,219 +16,318 @@ pub enum HashType {
|
|||
RIPEMD160
|
||||
}
|
||||
|
||||
pub fn evpmd(t: HashType) -> (*const ffi::EVP_MD, u32) {
|
||||
unsafe {
|
||||
match t {
|
||||
HashType::MD5 => (ffi::EVP_md5(), 16),
|
||||
HashType::SHA1 => (ffi::EVP_sha1(), 20),
|
||||
HashType::SHA224 => (ffi::EVP_sha224(), 28),
|
||||
HashType::SHA256 => (ffi::EVP_sha256(), 32),
|
||||
HashType::SHA384 => (ffi::EVP_sha384(), 48),
|
||||
HashType::SHA512 => (ffi::EVP_sha512(), 64),
|
||||
HashType::RIPEMD160 => (ffi::EVP_ripemd160(), 20),
|
||||
impl Type {
|
||||
/// Returns the length of the message digest.
|
||||
#[inline]
|
||||
pub fn md_len(&self) -> usize {
|
||||
use self::Type::*;
|
||||
match *self {
|
||||
MD5 => 16,
|
||||
SHA1 => 20,
|
||||
SHA224 => 28,
|
||||
SHA256 => 32,
|
||||
SHA384 => 48,
|
||||
SHA512 => 64,
|
||||
RIPEMD160 => 20,
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal interface subject to removal.
|
||||
#[inline]
|
||||
pub fn evp_md(&self) -> *const ffi::EVP_MD {
|
||||
unsafe {
|
||||
use self::Type::*;
|
||||
match *self {
|
||||
MD5 => ffi::EVP_md5(),
|
||||
SHA1 => ffi::EVP_sha1(),
|
||||
SHA224 => ffi::EVP_sha224(),
|
||||
SHA256 => ffi::EVP_sha256(),
|
||||
SHA384 => ffi::EVP_sha384(),
|
||||
SHA512 => ffi::EVP_sha512(),
|
||||
RIPEMD160 => ffi::EVP_ripemd160(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HasherContext {
|
||||
ptr: *mut ffi::EVP_MD_CTX
|
||||
#[derive(PartialEq, Copy)]
|
||||
enum State {
|
||||
Reset,
|
||||
Updated,
|
||||
Finalized,
|
||||
}
|
||||
|
||||
impl HasherContext {
|
||||
pub fn new() -> HasherContext {
|
||||
use self::State::*;
|
||||
|
||||
/// Provides message digest (hash) computation.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Calculate a hash in one go.
|
||||
///
|
||||
/// ```
|
||||
/// use openssl::crypto::hash::{hash, Type};
|
||||
/// let data = b"\x42\xF4\x97\xE0";
|
||||
/// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2";
|
||||
/// let res = hash(Type::MD5, data);
|
||||
/// assert_eq!(res, spec);
|
||||
/// ```
|
||||
///
|
||||
/// Use the `Writer` trait to supply the input in chunks.
|
||||
///
|
||||
/// ```
|
||||
/// use std::old_io::Writer;
|
||||
/// use openssl::crypto::hash::{Hasher, Type};
|
||||
/// let data = [b"\x42\xF4", b"\x97\xE0"];
|
||||
/// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2";
|
||||
/// let mut h = Hasher::new(Type::MD5);
|
||||
/// h.write_all(data[0]);
|
||||
/// h.write_all(data[1]);
|
||||
/// let res = h.finish();
|
||||
/// assert_eq!(res, spec);
|
||||
/// ```
|
||||
///
|
||||
/// # Warning
|
||||
///
|
||||
/// Don't actually use MD5 and SHA-1 hashes, they're not secure anymore.
|
||||
///
|
||||
/// Don't ever hash passwords, use `crypto::pkcs5` or bcrypt/scrypt instead.
|
||||
pub struct Hasher {
|
||||
ctx: *mut ffi::EVP_MD_CTX,
|
||||
md: *const ffi::EVP_MD,
|
||||
type_: Type,
|
||||
state: State,
|
||||
}
|
||||
|
||||
impl Hasher {
|
||||
/// Creates a new `Hasher` with the specified hash type.
|
||||
pub fn new(ty: Type) -> Hasher {
|
||||
ffi::init();
|
||||
|
||||
unsafe {
|
||||
HasherContext { ptr: ffi::EVP_MD_CTX_create() }
|
||||
let ctx = unsafe {
|
||||
let r = ffi::EVP_MD_CTX_create();
|
||||
assert!(!r.is_null());
|
||||
r
|
||||
};
|
||||
let md = ty.evp_md();
|
||||
|
||||
let mut h = Hasher { ctx: ctx, md: md, type_: ty, state: Finalized };
|
||||
h.init();
|
||||
h
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn init(&mut self) {
|
||||
match self.state {
|
||||
Reset => return,
|
||||
Updated => { self.finalize(); },
|
||||
Finalized => (),
|
||||
}
|
||||
unsafe {
|
||||
let r = ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *const _);
|
||||
assert_eq!(r, 1);
|
||||
}
|
||||
self.state = Reset;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn update(&mut self, data: &[u8]) {
|
||||
if self.state == Finalized {
|
||||
self.init();
|
||||
}
|
||||
unsafe {
|
||||
let r = ffi::EVP_DigestUpdate(self.ctx, data.as_ptr(),
|
||||
data.len() as c_uint);
|
||||
assert_eq!(r, 1);
|
||||
}
|
||||
self.state = Updated;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn finalize(&mut self) -> Vec<u8> {
|
||||
if self.state == Finalized {
|
||||
self.init();
|
||||
}
|
||||
let md_len = self.type_.md_len();
|
||||
let mut res: Vec<u8> = repeat(0).take(md_len).collect();
|
||||
unsafe {
|
||||
let mut len = 0;
|
||||
let r = ffi::EVP_DigestFinal_ex(self.ctx, res.as_mut_ptr(), &mut len);
|
||||
assert_eq!(len as usize, md_len);
|
||||
assert_eq!(r, 1);
|
||||
}
|
||||
self.state = Finalized;
|
||||
res
|
||||
}
|
||||
|
||||
/// Returns the hash of the data written since creation or
|
||||
/// the last `finish` and resets the hasher.
|
||||
#[inline]
|
||||
pub fn finish(&mut self) -> Vec<u8> {
|
||||
self.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HasherContext {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::EVP_MD_CTX_destroy(self.ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct Hasher {
|
||||
evp: *const ffi::EVP_MD,
|
||||
ctx: HasherContext,
|
||||
len: u32,
|
||||
}
|
||||
|
||||
impl old_io::Writer for Hasher {
|
||||
fn write_all(&mut self, buf: &[u8]) -> old_io::IoResult<()> {
|
||||
impl Writer for Hasher {
|
||||
#[inline]
|
||||
fn write_all(&mut self, buf: &[u8]) -> Result<(), IoError> {
|
||||
self.update(buf);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Hasher {
|
||||
pub fn new(ht: HashType) -> Hasher {
|
||||
let ctx = HasherContext::new();
|
||||
Hasher::with_context(ctx, ht)
|
||||
}
|
||||
|
||||
pub fn with_context(ctx: HasherContext, ht: HashType) -> Hasher {
|
||||
let (evp, mdlen) = evpmd(ht);
|
||||
unsafe {
|
||||
ffi::EVP_DigestInit_ex(ctx.ptr, evp, 0 as *const _);
|
||||
}
|
||||
|
||||
Hasher { evp: evp, ctx: ctx, len: mdlen }
|
||||
}
|
||||
|
||||
/// Update this hasher with more input bytes
|
||||
pub fn update(&mut self, data: &[u8]) {
|
||||
unsafe {
|
||||
ffi::EVP_DigestUpdate(self.ctx.ptr, data.as_ptr(), data.len() as c_uint);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the digest of all bytes added to this hasher since its last
|
||||
* initialization
|
||||
*/
|
||||
pub fn finalize(self) -> Vec<u8> {
|
||||
let (res, _) = self.finalize_reuse();
|
||||
res
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the digest of all bytes added to this hasher since its last
|
||||
* initialization and its context for reuse
|
||||
*/
|
||||
pub fn finalize_reuse(self) -> (Vec<u8>, HasherContext) {
|
||||
let mut res = repeat(0u8).take(self.len as usize).collect::<Vec<_>>();
|
||||
unsafe {
|
||||
ffi::EVP_DigestFinal_ex(self.ctx.ptr, res.as_mut_ptr(), ptr::null_mut())
|
||||
impl Clone for Hasher {
|
||||
fn clone(&self) -> Hasher {
|
||||
let ctx = unsafe {
|
||||
let ctx = ffi::EVP_MD_CTX_create();
|
||||
assert!(!ctx.is_null());
|
||||
let r = ffi::EVP_MD_CTX_copy_ex(ctx, self.ctx);
|
||||
assert_eq!(r, 1);
|
||||
ctx
|
||||
};
|
||||
(res, self.ctx)
|
||||
Hasher { ctx: ctx, md: self.md, type_: self.type_, state: self.state }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hashes the supplied input data using hash t, returning the resulting hash
|
||||
* value
|
||||
*/
|
||||
pub fn hash(t: HashType, data: &[u8]) -> Vec<u8> {
|
||||
impl Drop for Hasher {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if self.state != Finalized {
|
||||
let mut buf: Vec<u8> = repeat(0).take(self.type_.md_len()).collect();
|
||||
let mut len = 0;
|
||||
ffi::EVP_DigestFinal_ex(self.ctx, buf.as_mut_ptr(), &mut len);
|
||||
}
|
||||
ffi::EVP_MD_CTX_destroy(self.ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the hash of the `data` with the hash `t`.
|
||||
pub fn hash(t: Type, data: &[u8]) -> Vec<u8> {
|
||||
let mut h = Hasher::new(t);
|
||||
h.update(data);
|
||||
h.finalize()
|
||||
let _ = h.write_all(data);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serialize::hex::{FromHex, ToHex};
|
||||
use super::{hash, Hasher, Type};
|
||||
use std::old_io::Writer;
|
||||
|
||||
struct HashTest {
|
||||
input: Vec<u8>,
|
||||
expected_output: String
|
||||
fn hash_test(hashtype: Type, hashtest: &(&str, &str)) {
|
||||
let res = hash(hashtype, &*hashtest.0.from_hex().unwrap());
|
||||
assert_eq!(res.to_hex(), hashtest.1);
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
fn HashTest(input: &str, output: &str) -> HashTest {
|
||||
HashTest { input: input.from_hex().unwrap(),
|
||||
expected_output: output.to_string() }
|
||||
}
|
||||
|
||||
fn compare(calced_raw: Vec<u8>, hashtest: &HashTest) {
|
||||
let calced = calced_raw.as_slice().to_hex().to_string();
|
||||
|
||||
if calced != hashtest.expected_output {
|
||||
println!("Test failed - {} != {}", calced, hashtest.expected_output);
|
||||
}
|
||||
|
||||
assert!(calced == hashtest.expected_output);
|
||||
}
|
||||
|
||||
fn hash_test(hashtype: super::HashType, hashtest: &HashTest) {
|
||||
let calced_raw = super::hash(hashtype, hashtest.input.as_slice());
|
||||
compare(calced_raw, hashtest);
|
||||
}
|
||||
|
||||
fn hash_reuse_test(ctx: super::HasherContext, hashtype: super::HashType,
|
||||
hashtest: &HashTest) -> super::HasherContext {
|
||||
let mut h = super::Hasher::with_context(ctx, hashtype);
|
||||
h.update(hashtest.input.as_slice());
|
||||
let (calced_raw, ctx) = h.finalize_reuse();
|
||||
|
||||
compare(calced_raw, hashtest);
|
||||
|
||||
ctx
|
||||
}
|
||||
|
||||
pub fn hash_writer(t: super::HashType, data: &[u8]) -> Vec<u8> {
|
||||
let mut h = super::Hasher::new(t);
|
||||
h.write_all(data).unwrap();
|
||||
h.finalize()
|
||||
fn hash_recycle_test(h: &mut Hasher, hashtest: &(&str, &str)) {
|
||||
let _ = h.write_all(&*hashtest.0.from_hex().unwrap());
|
||||
let res = h.finish();
|
||||
assert_eq!(res.to_hex(), hashtest.1);
|
||||
}
|
||||
|
||||
// Test vectors from http://www.nsrl.nist.gov/testdata/
|
||||
#[allow(non_upper_case_globals)]
|
||||
const md5_tests: [(&'static str, &'static str); 13] = [
|
||||
("", "d41d8cd98f00b204e9800998ecf8427e"),
|
||||
("7F", "83acb6e67e50e31db6ed341dd2de1595"),
|
||||
("EC9C", "0b07f0d4ca797d8ac58874f887cb0b68"),
|
||||
("FEE57A", "e0d583171eb06d56198fc0ef22173907"),
|
||||
("42F497E0", "7c430f178aefdf1487fee7144e9641e2"),
|
||||
("C53B777F1C", "75ef141d64cb37ec423da2d9d440c925"),
|
||||
("89D5B576327B", "ebbaf15eb0ed784c6faa9dc32831bf33"),
|
||||
("5D4CCE781EB190", "ce175c4b08172019f05e6b5279889f2c"),
|
||||
("81901FE94932D7B9", "cd4d2f62b8cdb3a0cf968a735a239281"),
|
||||
("C9FFDEE7788EFB4EC9", "e0841a231ab698db30c6c0f3f246c014"),
|
||||
("66AC4B7EBA95E53DC10B", "a3b3cea71910d9af56742aa0bb2fe329"),
|
||||
("A510CD18F7A56852EB0319", "577e216843dd11573574d3fb209b97d8"),
|
||||
("AAED18DBE8938C19ED734A8D", "6f80fb775f27e0a4ce5c2f42fc72c5f1")
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn test_md5() {
|
||||
let tests = [
|
||||
HashTest("", "d41d8cd98f00b204e9800998ecf8427e"),
|
||||
HashTest("7F", "83acb6e67e50e31db6ed341dd2de1595"),
|
||||
HashTest("EC9C", "0b07f0d4ca797d8ac58874f887cb0b68"),
|
||||
HashTest("FEE57A", "e0d583171eb06d56198fc0ef22173907"),
|
||||
HashTest("42F497E0", "7c430f178aefdf1487fee7144e9641e2"),
|
||||
HashTest("C53B777F1C", "75ef141d64cb37ec423da2d9d440c925"),
|
||||
HashTest("89D5B576327B", "ebbaf15eb0ed784c6faa9dc32831bf33"),
|
||||
HashTest("5D4CCE781EB190", "ce175c4b08172019f05e6b5279889f2c"),
|
||||
HashTest("81901FE94932D7B9", "cd4d2f62b8cdb3a0cf968a735a239281"),
|
||||
HashTest("C9FFDEE7788EFB4EC9", "e0841a231ab698db30c6c0f3f246c014"),
|
||||
HashTest("66AC4B7EBA95E53DC10B", "a3b3cea71910d9af56742aa0bb2fe329"),
|
||||
HashTest("A510CD18F7A56852EB0319", "577e216843dd11573574d3fb209b97d8"),
|
||||
HashTest("AAED18DBE8938C19ED734A8D", "6f80fb775f27e0a4ce5c2f42fc72c5f1")];
|
||||
|
||||
let mut ctx = super::HasherContext::new();
|
||||
|
||||
for test in tests.iter() {
|
||||
ctx = hash_reuse_test(ctx, super::HashType::MD5, test);
|
||||
for test in md5_tests.iter() {
|
||||
hash_test(Type::MD5, test);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_md5_recycle() {
|
||||
let mut h = Hasher::new(Type::MD5);
|
||||
for test in md5_tests.iter() {
|
||||
hash_recycle_test(&mut h, test);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_finish_twice() {
|
||||
let mut h = Hasher::new(Type::MD5);
|
||||
let _ = h.write_all(&*md5_tests[6].0.from_hex().unwrap());
|
||||
let _ = h.finish();
|
||||
let res = h.finish();
|
||||
let null = hash(Type::MD5, &[]);
|
||||
assert_eq!(res, null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clone() {
|
||||
let i = 7;
|
||||
let inp = md5_tests[i].0.from_hex().unwrap();
|
||||
assert!(inp.len() > 2);
|
||||
let p = inp.len() / 2;
|
||||
let h0 = Hasher::new(Type::MD5);
|
||||
|
||||
println!("Clone a new hasher");
|
||||
let mut h1 = h0.clone();
|
||||
let _ = h1.write_all(&inp[..p]);
|
||||
{
|
||||
println!("Clone an updated hasher");
|
||||
let mut h2 = h1.clone();
|
||||
let _ = h2.write_all(&inp[p..]);
|
||||
let res = h2.finish();
|
||||
assert_eq!(res.to_hex(), md5_tests[i].1);
|
||||
}
|
||||
let _ = h1.write_all(&inp[p..]);
|
||||
let res = h1.finish();
|
||||
assert_eq!(res.to_hex(), md5_tests[i].1);
|
||||
|
||||
println!("Clone a finished hasher");
|
||||
let mut h3 = h1.clone();
|
||||
let _ = h3.write_all(&*md5_tests[i + 1].0.from_hex().unwrap());
|
||||
let res = h3.finish();
|
||||
assert_eq!(res.to_hex(), md5_tests[i + 1].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sha1() {
|
||||
let tests = [
|
||||
HashTest("616263", "a9993e364706816aba3e25717850c26c9cd0d89d"),
|
||||
("616263", "a9993e364706816aba3e25717850c26c9cd0d89d"),
|
||||
];
|
||||
|
||||
for test in tests.iter() {
|
||||
hash_test(super::HashType::SHA1, test);
|
||||
hash_test(Type::SHA1, test);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sha256() {
|
||||
let tests = [
|
||||
HashTest("616263", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
||||
("616263", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
|
||||
];
|
||||
|
||||
for test in tests.iter() {
|
||||
hash_test(super::HashType::SHA256, test);
|
||||
hash_test(Type::SHA256, test);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ripemd160() {
|
||||
let tests = [
|
||||
HashTest("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")
|
||||
("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")
|
||||
];
|
||||
|
||||
for test in tests.iter() {
|
||||
hash_test(super::HashType::RIPEMD160, test);
|
||||
hash_test(Type::RIPEMD160, test);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_writer() {
|
||||
let tv = "rust-openssl".as_bytes();
|
||||
let ht = super::HashType::RIPEMD160;
|
||||
assert!(hash_writer(ht, tv) == super::hash(ht, tv));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,66 +16,201 @@
|
|||
|
||||
use libc::{c_int, c_uint};
|
||||
use std::iter::repeat;
|
||||
use std::old_io::{IoError, Writer};
|
||||
|
||||
use crypto::hash;
|
||||
use crypto::hash::Type;
|
||||
use ffi;
|
||||
|
||||
pub struct HMAC {
|
||||
ctx: ffi::HMAC_CTX,
|
||||
len: u32,
|
||||
#[derive(PartialEq, Copy)]
|
||||
enum State {
|
||||
Reset,
|
||||
Updated,
|
||||
Finalized,
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub fn HMAC(ht: hash::HashType, key: &[u8]) -> HMAC {
|
||||
unsafe {
|
||||
ffi::init();
|
||||
use self::State::*;
|
||||
|
||||
let (evp, mdlen) = hash::evpmd(ht);
|
||||
|
||||
let mut ctx : ffi::HMAC_CTX = ::std::mem::uninitialized();
|
||||
|
||||
ffi::HMAC_CTX_init(&mut ctx);
|
||||
ffi::HMAC_Init_ex(&mut ctx,
|
||||
key.as_ptr(),
|
||||
key.len() as c_int,
|
||||
evp, 0 as *const _);
|
||||
|
||||
HMAC { ctx: ctx, len: mdlen }
|
||||
}
|
||||
/// Provides HMAC computation.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Calculate a HMAC in one go.
|
||||
///
|
||||
/// ```
|
||||
/// use openssl::crypto::hash::Type;
|
||||
/// use openssl::crypto::hmac::hmac;
|
||||
/// let key = b"Jefe";
|
||||
/// let data = b"what do ya want for nothing?";
|
||||
/// let spec = b"\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38";
|
||||
/// let res = hmac(Type::MD5, key, data);
|
||||
/// assert_eq!(spec, res);
|
||||
/// ```
|
||||
///
|
||||
/// Use the `Writer` trait to supply the input in chunks.
|
||||
///
|
||||
/// ```
|
||||
/// use std::old_io::Writer;
|
||||
/// use openssl::crypto::hash::Type;
|
||||
/// use openssl::crypto::hmac::HMAC;
|
||||
/// let key = b"Jefe";
|
||||
/// let data = [b"what do ya ", b"want for nothing?"];
|
||||
/// let spec = b"\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38";
|
||||
/// let mut h = HMAC::new(Type::MD5, &*key);
|
||||
/// h.write_all(data[0]);
|
||||
/// h.write_all(data[1]);
|
||||
/// let res = h.finish();
|
||||
/// assert_eq!(spec, res);
|
||||
/// ```
|
||||
pub struct HMAC {
|
||||
ctx: ffi::HMAC_CTX,
|
||||
type_: Type,
|
||||
state: State,
|
||||
}
|
||||
|
||||
impl HMAC {
|
||||
pub fn update(&mut self, data: &[u8]) {
|
||||
unsafe {
|
||||
ffi::HMAC_Update(&mut self.ctx, data.as_ptr(), data.len() as c_uint);
|
||||
}
|
||||
/// Creates a new `HMAC` with the specified hash type using the `key`.
|
||||
pub fn new(ty: Type, key: &[u8]) -> HMAC {
|
||||
ffi::init();
|
||||
|
||||
let ctx = unsafe {
|
||||
let mut ctx = ::std::mem::uninitialized();
|
||||
ffi::HMAC_CTX_init(&mut ctx);
|
||||
ctx
|
||||
};
|
||||
let md = ty.evp_md();
|
||||
|
||||
let mut h = HMAC { ctx: ctx, type_: ty, state: Finalized };
|
||||
h.init_once(md, key);
|
||||
h
|
||||
}
|
||||
|
||||
pub fn finalize(&mut self) -> Vec<u8> {
|
||||
#[inline]
|
||||
fn init_once(&mut self, md: *const ffi::EVP_MD, key: &[u8]) {
|
||||
unsafe {
|
||||
let mut res: Vec<u8> = repeat(0).take(self.len as usize).collect();
|
||||
let mut outlen = 0;
|
||||
ffi::HMAC_Final(&mut self.ctx, res.as_mut_ptr(), &mut outlen);
|
||||
assert!(self.len == outlen as u32);
|
||||
res
|
||||
let r = ffi::HMAC_Init_ex(&mut self.ctx,
|
||||
key.as_ptr(), key.len() as c_int,
|
||||
md, 0 as *const _);
|
||||
assert_eq!(r, 1);
|
||||
}
|
||||
self.state = Reset;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn init(&mut self) {
|
||||
match self.state {
|
||||
Reset => return,
|
||||
Updated => { self.finalize(); },
|
||||
Finalized => (),
|
||||
}
|
||||
// If the key and/or md is not supplied it's reused from the last time
|
||||
// avoiding redundant initializations
|
||||
unsafe {
|
||||
let r = ffi::HMAC_Init_ex(&mut self.ctx,
|
||||
0 as *const _, 0,
|
||||
0 as *const _, 0 as *const _);
|
||||
assert_eq!(r, 1);
|
||||
}
|
||||
self.state = Reset;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn update(&mut self, data: &[u8]) {
|
||||
if self.state == Finalized {
|
||||
self.init();
|
||||
}
|
||||
unsafe {
|
||||
let r = ffi::HMAC_Update(&mut self.ctx, data.as_ptr(),
|
||||
data.len() as c_uint);
|
||||
assert_eq!(r, 1);
|
||||
}
|
||||
self.state = Updated;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn finalize(&mut self) -> Vec<u8> {
|
||||
if self.state == Finalized {
|
||||
self.init();
|
||||
}
|
||||
let md_len = self.type_.md_len();
|
||||
let mut res: Vec<u8> = repeat(0).take(md_len).collect();
|
||||
unsafe {
|
||||
let mut len = 0;
|
||||
let r = ffi::HMAC_Final(&mut self.ctx, res.as_mut_ptr(), &mut len);
|
||||
assert_eq!(len as usize, md_len);
|
||||
assert_eq!(r, 1);
|
||||
}
|
||||
self.state = Finalized;
|
||||
res
|
||||
}
|
||||
|
||||
/// Returns the hash of the data written since creation or
|
||||
/// the last `finish` and resets the hasher.
|
||||
#[inline]
|
||||
pub fn finish(&mut self) -> Vec<u8> {
|
||||
self.finalize()
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer for HMAC {
|
||||
#[inline]
|
||||
fn write_all(&mut self, buf: &[u8]) -> Result<(), IoError> {
|
||||
self.update(buf);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for HMAC {
|
||||
fn clone(&self) -> HMAC {
|
||||
let mut ctx: ffi::HMAC_CTX;
|
||||
unsafe {
|
||||
ctx = ::std::mem::uninitialized();
|
||||
let r = ffi::HMAC_CTX_copy(&mut ctx, &self.ctx);
|
||||
assert_eq!(r, 1);
|
||||
}
|
||||
HMAC { ctx: ctx, type_: self.type_, state: self.state }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HMAC {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if self.state != Finalized {
|
||||
let mut buf: Vec<u8> = repeat(0).take(self.type_.md_len()).collect();
|
||||
let mut len = 0;
|
||||
ffi::HMAC_Final(&mut self.ctx, buf.as_mut_ptr(), &mut len);
|
||||
}
|
||||
ffi::HMAC_CTX_cleanup(&mut self.ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the HMAC of the `data` with the hash `t` and `key`.
|
||||
pub fn hmac(t: Type, key: &[u8], data: &[u8]) -> Vec<u8> {
|
||||
let mut h = HMAC::new(t, key);
|
||||
let _ = h.write_all(data);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::iter::repeat;
|
||||
use serialize::hex::FromHex;
|
||||
use crypto::hash::HashType::{self, MD5, SHA1, SHA224, SHA256, SHA384, SHA512};
|
||||
use super::HMAC;
|
||||
use crypto::hash::Type;
|
||||
use crypto::hash::Type::*;
|
||||
use super::{hmac, HMAC};
|
||||
use std::old_io::Writer;
|
||||
|
||||
fn test_hmac(ty: Type, tests: &[(Vec<u8>, Vec<u8>, Vec<u8>)]) {
|
||||
for &(ref key, ref data, ref res) in tests.iter() {
|
||||
assert_eq!(hmac(ty, &**key, &**data), *res);
|
||||
}
|
||||
}
|
||||
|
||||
fn test_hmac_recycle(h: &mut HMAC, test: &(Vec<u8>, Vec<u8>, Vec<u8>)) {
|
||||
let &(_, ref data, ref res) = test;
|
||||
let _ = h.write_all(&**data);
|
||||
assert_eq!(h.finish(), *res);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hmac_md5() {
|
||||
|
|
@ -103,13 +238,78 @@ mod tests {
|
|||
"6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())
|
||||
];
|
||||
|
||||
for &(ref key, ref data, ref res) in tests.iter() {
|
||||
let mut hmac = HMAC(MD5, key.as_slice());
|
||||
hmac.update(data.as_slice());
|
||||
assert_eq!(hmac.finalize(), *res);
|
||||
test_hmac(MD5, &tests);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hmac_md5_recycle() {
|
||||
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] = [
|
||||
(repeat(0xaa_u8).take(80).collect(),
|
||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
|
||||
(repeat(0xaa_u8).take(80).collect(),
|
||||
b"Test Using Larger Than Block-Size Key \
|
||||
and Larger Than One Block-Size Data".to_vec(),
|
||||
"6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap())
|
||||
];
|
||||
|
||||
let mut h = HMAC::new(MD5, &*tests[0].0);
|
||||
for i in 0..100us {
|
||||
let test = &tests[i % 2];
|
||||
test_hmac_recycle(&mut h, test);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_finish_twice() {
|
||||
let test: (Vec<u8>, Vec<u8>, Vec<u8>) =
|
||||
(repeat(0xaa_u8).take(80).collect(),
|
||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap());
|
||||
|
||||
let mut h = HMAC::new(Type::MD5, &*test.0);
|
||||
let _ = h.write_all(&*test.1);
|
||||
let _ = h.finish();
|
||||
let res = h.finish();
|
||||
let null = hmac(Type::MD5, &*test.0, &[]);
|
||||
assert_eq!(res, null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clone() {
|
||||
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] = [
|
||||
(repeat(0xaa_u8).take(80).collect(),
|
||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||
"6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd".from_hex().unwrap()),
|
||||
(repeat(0xaa_u8).take(80).collect(),
|
||||
b"Test Using Larger Than Block-Size Key \
|
||||
and Larger Than One Block-Size Data".to_vec(),
|
||||
"6f630fad67cda0ee1fb1f562db3aa53e".from_hex().unwrap()),
|
||||
];
|
||||
let p = tests[0].0.len() / 2;
|
||||
let h0 = HMAC::new(Type::MD5, &*tests[0].0);
|
||||
|
||||
println!("Clone a new hmac");
|
||||
let mut h1 = h0.clone();
|
||||
let _ = h1.write_all(&tests[0].1[..p]);
|
||||
{
|
||||
println!("Clone an updated hmac");
|
||||
let mut h2 = h1.clone();
|
||||
let _ = h2.write_all(&tests[0].1[p..]);
|
||||
let res = h2.finish();
|
||||
assert_eq!(res, tests[0].2);
|
||||
}
|
||||
let _ = h1.write_all(&tests[0].1[p..]);
|
||||
let res = h1.finish();
|
||||
assert_eq!(res, tests[0].2);
|
||||
|
||||
println!("Clone a finished hmac");
|
||||
let mut h3 = h1.clone();
|
||||
let _ = h3.write_all(&*tests[1].1);
|
||||
let res = h3.finish();
|
||||
assert_eq!(res, tests[1].2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hmac_sha1() {
|
||||
// test vectors from RFC 2202
|
||||
|
|
@ -136,14 +336,31 @@ mod tests {
|
|||
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())
|
||||
];
|
||||
|
||||
for &(ref key, ref data, ref res) in tests.iter() {
|
||||
let mut hmac = HMAC(SHA1, key.as_slice());
|
||||
hmac.update(data.as_slice());
|
||||
assert_eq!(hmac.finalize(), *res);
|
||||
test_hmac(SHA1, &tests);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hmac_sha1_recycle() {
|
||||
let tests: [(Vec<u8>, Vec<u8>, Vec<u8>); 2] = [
|
||||
(repeat(0xaa_u8).take(80).collect(),
|
||||
b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(),
|
||||
"aa4ae5e15272d00e95705637ce8a3b55ed402112".from_hex().unwrap()),
|
||||
(repeat(0xaa_u8).take(80).collect(),
|
||||
b"Test Using Larger Than Block-Size Key \
|
||||
and Larger Than One Block-Size Data".to_vec(),
|
||||
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91".from_hex().unwrap())
|
||||
];
|
||||
|
||||
let mut h = HMAC::new(SHA1, &*tests[0].0);
|
||||
for i in 0..100us {
|
||||
let test = &tests[i % 2];
|
||||
test_hmac_recycle(&mut h, test);
|
||||
}
|
||||
}
|
||||
|
||||
fn test_sha2(ty: HashType, results: &[Vec<u8>]) {
|
||||
|
||||
|
||||
fn test_sha2(ty: Type, results: &[Vec<u8>]) {
|
||||
// test vectors from RFC 4231
|
||||
let tests: [(Vec<u8>, Vec<u8>); 6] = [
|
||||
(repeat(0xb_u8).take(20).collect(), b"Hi There".to_vec()),
|
||||
|
|
@ -161,9 +378,15 @@ mod tests {
|
|||
];
|
||||
|
||||
for (&(ref key, ref data), res) in tests.iter().zip(results.iter()) {
|
||||
let mut hmac = HMAC(ty, key.as_slice());
|
||||
hmac.update(data.as_slice());
|
||||
assert_eq!(hmac.finalize(), *res);
|
||||
assert_eq!(hmac(ty, &**key, &**data), *res);
|
||||
}
|
||||
|
||||
// recycle test
|
||||
let mut h = HMAC::new(ty, &*tests[5].0);
|
||||
for i in 0..100us {
|
||||
let test = &tests[4 + i % 2];
|
||||
let tup = (test.0.clone(), test.1.clone(), results[4 + i % 2].clone());
|
||||
test_hmac_recycle(&mut h, &tup);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@ use std::iter::repeat;
|
|||
use std::mem;
|
||||
use std::ptr;
|
||||
use bio::{MemBio};
|
||||
use crypto::hash::HashType;
|
||||
use crypto::hash;
|
||||
use crypto::hash::Type as HashType;
|
||||
use ffi;
|
||||
use ssl::error::{SslError, StreamError};
|
||||
|
||||
|
|
@ -276,7 +277,7 @@ impl PKey {
|
|||
*/
|
||||
pub fn verify(&self, m: &[u8], s: &[u8]) -> bool { self.verify_with_hash(m, s, HashType::SHA256) }
|
||||
|
||||
pub fn sign_with_hash(&self, s: &[u8], hash: HashType) -> Vec<u8> {
|
||||
pub fn sign_with_hash(&self, s: &[u8], hash: hash::Type) -> Vec<u8> {
|
||||
unsafe {
|
||||
let rsa = ffi::EVP_PKEY_get1_RSA(self.evp);
|
||||
let len = ffi::RSA_size(rsa);
|
||||
|
|
@ -300,7 +301,7 @@ impl PKey {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn verify_with_hash(&self, m: &[u8], s: &[u8], hash: HashType) -> bool {
|
||||
pub fn verify_with_hash(&self, m: &[u8], s: &[u8], hash: hash::Type) -> bool {
|
||||
unsafe {
|
||||
let rsa = ffi::EVP_PKEY_get1_RSA(self.evp);
|
||||
|
||||
|
|
@ -332,7 +333,7 @@ impl Drop for PKey {
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crypto::hash::HashType::{MD5, SHA1};
|
||||
use crypto::hash::Type::{MD5, SHA1};
|
||||
|
||||
#[test]
|
||||
fn test_gen_pub() {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ use std::old_io::net::tcp::TcpStream;
|
|||
use std::old_io::{Writer};
|
||||
use std::thread::Thread;
|
||||
|
||||
use crypto::hash::HashType::{SHA256};
|
||||
use crypto::hash::Type::{SHA256};
|
||||
use ssl::SslMethod::Sslv23;
|
||||
use ssl::{SslContext, SslStream, VerifyCallback};
|
||||
use ssl::SslVerifyMode::SslVerifyPeer;
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ use std::ptr;
|
|||
|
||||
use asn1::{Asn1Time};
|
||||
use bio::{MemBio};
|
||||
use crypto::hash::{HashType, evpmd};
|
||||
use crypto::hash;
|
||||
use crypto::hash::Type as HashType;
|
||||
use crypto::pkey::{PKey};
|
||||
use crypto::rand::rand_bytes;
|
||||
use ffi;
|
||||
|
|
@ -152,14 +153,14 @@ impl<'a, T: AsStr<'a>> ToStr for Vec<T> {
|
|||
/// use std::old_io::{File, Open, Write};
|
||||
/// # use std::old_io::fs;
|
||||
///
|
||||
/// use openssl::crypto::hash::HashType;
|
||||
/// use openssl::crypto::hash::Type;
|
||||
/// use openssl::x509::{KeyUsage, X509Generator};
|
||||
///
|
||||
/// let gen = X509Generator::new()
|
||||
/// .set_bitlength(2048)
|
||||
/// .set_valid_period(365*2)
|
||||
/// .set_CN("SuperMegaCorp Inc.")
|
||||
/// .set_sign_hash(HashType::SHA256)
|
||||
/// .set_sign_hash(Type::SHA256)
|
||||
/// .set_usage(&[KeyUsage::DigitalSignature]);
|
||||
///
|
||||
/// let (cert, pkey) = gen.generate().unwrap();
|
||||
|
|
@ -236,7 +237,7 @@ impl X509Generator {
|
|||
self
|
||||
}
|
||||
|
||||
pub fn set_sign_hash(mut self, hash_type: HashType) -> X509Generator {
|
||||
pub fn set_sign_hash(mut self, hash_type: hash::Type) -> X509Generator {
|
||||
self.hash_type = hash_type;
|
||||
self
|
||||
}
|
||||
|
|
@ -331,7 +332,7 @@ impl X509Generator {
|
|||
self.ext_key_usage.to_str().as_slice()));
|
||||
}
|
||||
|
||||
let (hash_fn, _) = evpmd(self.hash_type);
|
||||
let hash_fn = self.hash_type.evp_md();
|
||||
try_ssl!(ffi::X509_sign(x509.handle, p_key.get_handle(), hash_fn));
|
||||
Ok((x509, p_key))
|
||||
}
|
||||
|
|
@ -387,8 +388,9 @@ impl<'ctx> X509<'ctx> {
|
|||
}
|
||||
|
||||
/// Returns certificate fingerprint calculated using provided hash
|
||||
pub fn fingerprint(&self, hash_type: HashType) -> Option<Vec<u8>> {
|
||||
let (evp, len) = evpmd(hash_type);
|
||||
pub fn fingerprint(&self, hash_type: hash::Type) -> Option<Vec<u8>> {
|
||||
let evp = hash_type.evp_md();
|
||||
let len = hash_type.md_len();
|
||||
let v: Vec<u8> = repeat(0).take(len as usize).collect();
|
||||
let act_len: c_uint = 0;
|
||||
let res = unsafe {
|
||||
|
|
@ -399,7 +401,7 @@ impl<'ctx> X509<'ctx> {
|
|||
match res {
|
||||
0 => None,
|
||||
_ => {
|
||||
let act_len = act_len as u32;
|
||||
let act_len = act_len as usize;
|
||||
match len.cmp(&act_len) {
|
||||
Ordering::Greater => None,
|
||||
Ordering::Equal => Some(v),
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ use serialize::hex::FromHex;
|
|||
use std::old_io::{File, Open, Read};
|
||||
use std::old_io::util::NullWriter;
|
||||
|
||||
use crypto::hash::HashType::{SHA256};
|
||||
use crypto::hash::Type::{SHA256};
|
||||
use x509::{X509, X509Generator};
|
||||
use x509::KeyUsage::{DigitalSignature, KeyEncipherment};
|
||||
use x509::ExtKeyUsage::{ClientAuth, ServerAuth};
|
||||
|
|
|
|||
Loading…
Reference in New Issue