Merge pull request #2 from erickt/master

Merging up
This commit is contained in:
Kevin Ballard 2013-08-15 12:30:54 -07:00
commit e86deeb4d6
7 changed files with 328 additions and 291 deletions

View File

@ -1,7 +1,7 @@
crypto: crypto.rc $(wildcard *.rs) crypto: $(wildcard *.rs)
rustc crypto.rc rustc crypto.rs
rustc --test crypto.rc rustc --test crypto.rs
clean: clean:
rm -f crypto libcrypto-*.so rm -f crypto libcrypto-*.so

View File

@ -20,8 +20,8 @@
uuid = "38297409-b4c2-4499-8131-a99a7e44dad3")]; uuid = "38297409-b4c2-4499-8131-a99a7e44dad3")];
#[crate_type = "lib"]; #[crate_type = "lib"];
pub mod hex;
pub mod hash; pub mod hash;
pub mod hex;
pub mod hmac; pub mod hmac;
pub mod pkcs5; pub mod pkcs5;
pub mod pkey; pub mod pkey;

94
hash.rs
View File

@ -1,5 +1,7 @@
use std::libc::c_uint; use std::libc::c_uint;
use std::{libc,vec,ptr}; use std::libc;
use std::ptr;
use std::vec;
pub enum HashType { pub enum HashType {
MD5, MD5,
@ -16,32 +18,37 @@ pub type EVP_MD_CTX = *libc::c_void;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
pub type EVP_MD = *libc::c_void; pub type EVP_MD = *libc::c_void;
#[abi = "cdecl"] mod libcrypto {
#[link_args = "-lcrypto"] use super::*;
extern { use std::libc::c_uint;
fn EVP_MD_CTX_create() -> EVP_MD_CTX;
fn EVP_md5() -> EVP_MD; #[link_args = "-lcrypto"]
fn EVP_sha1() -> EVP_MD; extern {
fn EVP_sha224() -> EVP_MD; fn EVP_MD_CTX_create() -> EVP_MD_CTX;
fn EVP_sha256() -> EVP_MD; fn EVP_MD_CTX_destroy(ctx: EVP_MD_CTX);
fn EVP_sha384() -> EVP_MD;
fn EVP_sha512() -> EVP_MD;
fn EVP_DigestInit(ctx: EVP_MD_CTX, typ: EVP_MD); fn EVP_md5() -> EVP_MD;
fn EVP_DigestUpdate(ctx: EVP_MD_CTX, data: *u8, n: c_uint); fn EVP_sha1() -> EVP_MD;
fn EVP_DigestFinal(ctx: EVP_MD_CTX, res: *mut u8, n: *u32); fn EVP_sha224() -> EVP_MD;
fn EVP_sha256() -> EVP_MD;
fn EVP_sha384() -> EVP_MD;
fn EVP_sha512() -> EVP_MD;
fn EVP_DigestInit(ctx: EVP_MD_CTX, typ: EVP_MD);
fn EVP_DigestUpdate(ctx: EVP_MD_CTX, data: *u8, n: c_uint);
fn EVP_DigestFinal(ctx: EVP_MD_CTX, res: *mut u8, n: *u32);
}
} }
pub fn evpmd(t: HashType) -> (EVP_MD, uint) { pub fn evpmd(t: HashType) -> (EVP_MD, uint) {
unsafe { unsafe {
match t { match t {
MD5 => (EVP_md5(), 16u), MD5 => (libcrypto::EVP_md5(), 16u),
SHA1 => (EVP_sha1(), 20u), SHA1 => (libcrypto::EVP_sha1(), 20u),
SHA224 => (EVP_sha224(), 28u), SHA224 => (libcrypto::EVP_sha224(), 28u),
SHA256 => (EVP_sha256(), 32u), SHA256 => (libcrypto::EVP_sha256(), 32u),
SHA384 => (EVP_sha384(), 48u), SHA384 => (libcrypto::EVP_sha384(), 48u),
SHA512 => (EVP_sha512(), 64u), SHA512 => (libcrypto::EVP_sha512(), 64u),
} }
} }
} }
@ -52,29 +59,22 @@ pub struct Hasher {
priv len: uint, priv len: uint,
} }
pub fn Hasher(ht: HashType) -> Hasher {
unsafe {
let ctx = EVP_MD_CTX_create();
let (evp, mdlen) = evpmd(ht);
let h = Hasher { evp: evp, ctx: ctx, len: mdlen };
h.init();
h
}
}
impl Hasher { impl Hasher {
/// Initializes this hasher pub fn new(ht: HashType) -> Hasher {
pub fn init(&self) { let ctx = unsafe { libcrypto::EVP_MD_CTX_create() };
let (evp, mdlen) = evpmd(ht);
unsafe { unsafe {
EVP_DigestInit(self.ctx, self.evp); libcrypto::EVP_DigestInit(ctx, evp);
} }
Hasher { evp: evp, ctx: ctx, len: mdlen }
} }
/// Update this hasher with more input bytes /// Update this hasher with more input bytes
pub fn update(&self, data: &[u8]) { pub fn update(&self, data: &[u8]) {
unsafe { do data.as_imm_buf |pdata, len| {
do data.as_imm_buf |pdata, len| { unsafe {
EVP_DigestUpdate(self.ctx, pdata, len as c_uint) libcrypto::EVP_DigestUpdate(self.ctx, pdata, len as c_uint)
} }
} }
} }
@ -84,12 +84,20 @@ impl Hasher {
* initialization * initialization
*/ */
pub fn final(&self) -> ~[u8] { pub fn final(&self) -> ~[u8] {
unsafe { let mut res = vec::from_elem(self.len, 0u8);
let mut res = vec::from_elem(self.len, 0u8); do res.as_mut_buf |pres, _len| {
do res.as_mut_buf |pres, _len| { unsafe {
EVP_DigestFinal(self.ctx, pres, ptr::null()); libcrypto::EVP_DigestFinal(self.ctx, pres, ptr::null());
} }
res }
res
}
}
impl Drop for Hasher {
fn drop(&self) {
unsafe {
libcrypto::EVP_MD_CTX_destroy(self.ctx);
} }
} }
} }
@ -99,7 +107,7 @@ impl Hasher {
* value * value
*/ */
pub fn hash(t: HashType, data: &[u8]) -> ~[u8] { pub fn hash(t: HashType, data: &[u8]) -> ~[u8] {
let h = Hasher(t); let h = Hasher::new(t);
h.update(data); h.update(data);
h.final() h.final()
} }
@ -135,7 +143,6 @@ mod tests {
// Test vectors from http://www.nsrl.nist.gov/testdata/ // Test vectors from http://www.nsrl.nist.gov/testdata/
#[test] #[test]
fn test_md5() { fn test_md5() {
let tests = [ let tests = [
HashTest(~"", ~"D41D8CD98F00B204E9800998ECF8427E"), HashTest(~"", ~"D41D8CD98F00B204E9800998ECF8427E"),
HashTest(~"7F", ~"83ACB6E67E50E31DB6ED341DD2DE1595"), HashTest(~"7F", ~"83ACB6E67E50E31DB6ED341DD2DE1595"),
@ -158,7 +165,6 @@ mod tests {
#[test] #[test]
fn test_sha1() { fn test_sha1() {
let tests = [ let tests = [
HashTest(~"616263", ~"A9993E364706816ABA3E25717850C26C9CD0D89D"), HashTest(~"616263", ~"A9993E364706816ABA3E25717850C26C9CD0D89D"),
]; ];

167
pkcs5.rs
View File

@ -1,13 +1,16 @@
use std::libc::c_int; use std::libc::c_int;
use std::vec; use std::vec;
#[link_args = "-lcrypto"] mod libcrypto {
#[abi = "cdecl"] use std::libc::c_int;
extern {
fn PKCS5_PBKDF2_HMAC_SHA1(pass: *u8, passlen: c_int, #[link_args = "-lcrypto"]
salt: *u8, saltlen: c_int, extern {
iter: c_int, keylen: c_int, fn PKCS5_PBKDF2_HMAC_SHA1(pass: *u8, passlen: c_int,
out: *mut u8) -> c_int; salt: *u8, saltlen: c_int,
iter: c_int, keylen: c_int,
out: *mut u8) -> c_int;
}
} }
#[doc = " #[doc = "
@ -23,15 +26,15 @@ pub fn pbkdf2_hmac_sha1(pass: &str, salt: &[u8], iter: uint,
let mut out = vec::with_capacity(keylen); let mut out = vec::with_capacity(keylen);
do out.as_mut_buf |out_buf, _out_len| { do out.as_mut_buf |out_buf, _out_len| {
unsafe { let r = unsafe {
let r = PKCS5_PBKDF2_HMAC_SHA1( libcrypto::PKCS5_PBKDF2_HMAC_SHA1(
pass_buf, pass_len as c_int, pass_buf, pass_len as c_int,
salt_buf, salt_len as c_int, salt_buf, salt_len as c_int,
iter as c_int, keylen as c_int, iter as c_int, keylen as c_int,
out_buf); out_buf)
};
if r != 1 as c_int { fail!(); } if r != 1 as c_int { fail!(); }
}
} }
unsafe { vec::raw::set_len(&mut out, keylen); } unsafe { vec::raw::set_len(&mut out, keylen); }
@ -49,71 +52,89 @@ 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!(pbkdf2_hmac_sha1( assert_eq!(
"password", pbkdf2_hmac_sha1(
"salt".as_bytes(), "password",
1u, "salt".as_bytes(),
20u 1u,
) == ~[ 20u
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 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!(pbkdf2_hmac_sha1( assert_eq!(
"password", pbkdf2_hmac_sha1(
"salt".as_bytes(), "password",
2u, "salt".as_bytes(),
20u 2u,
) == ~[ 20u
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 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!(pbkdf2_hmac_sha1( assert_eq!(
"password", pbkdf2_hmac_sha1(
"salt".as_bytes(), "password",
4096u, "salt".as_bytes(),
20u 4096u,
) == ~[ 20u
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 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!(pbkdf2_hmac_sha1( assert_eq!(
"password", pbkdf2_hmac_sha1(
"salt".as_bytes(), "password",
16777216u, "salt".as_bytes(),
20u 16777216u,
) == ~[ 20u
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 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!(pbkdf2_hmac_sha1( assert_eq!(
"passwordPASSWORDpassword", pbkdf2_hmac_sha1(
"saltSALTsaltSALTsaltSALTsaltSALTsalt".as_bytes(), "passwordPASSWORDpassword",
4096u, "saltSALTsaltSALTsaltSALTsaltSALTsalt".as_bytes(),
25u 4096u,
) == ~[ 25u
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, 0x3d_u8, 0x2e_u8, 0xec_u8, 0x4f_u8, 0xe4_u8, 0x1c_u8, 0x84_u8,
0xf2_u8, 0xf0_u8, 0x70_u8, 0x38_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!(pbkdf2_hmac_sha1( assert_eq!(
"pass\x00word", pbkdf2_hmac_sha1(
"sa\x00lt".as_bytes(), "pass\x00word",
4096u, "sa\x00lt".as_bytes(),
16u 4096u,
) == ~[ 16u
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 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
]
);
} }
} }

222
pkey.rs
View File

@ -1,40 +1,44 @@
use std::cast;
use std::libc::{c_int, c_uint}; use std::libc::{c_int, c_uint};
use std::{libc,cast,ptr,vec}; use std::libc;
use std::ptr;
use std::vec;
use hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512}; use hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512};
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
type EVP_PKEY = *libc::c_void; pub type EVP_PKEY = *libc::c_void;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
type ANYKEY = *libc::c_void; pub type RSA = *libc::c_void;
#[allow(non_camel_case_types)] mod libcrypto {
type RSA = *libc::c_void; use super::*;
use std::libc::{c_char, c_int, c_uint};
#[link_args = "-lcrypto"] #[link_args = "-lcrypto"]
#[abi = "cdecl"] extern {
extern { fn EVP_PKEY_new() -> *EVP_PKEY;
fn EVP_PKEY_new() -> *EVP_PKEY; fn EVP_PKEY_free(k: *EVP_PKEY);
fn EVP_PKEY_free(k: *EVP_PKEY); fn EVP_PKEY_assign(pkey: *EVP_PKEY, typ: c_int, key: *c_char) -> c_int;
fn EVP_PKEY_assign(k: *EVP_PKEY, t: c_int, inner: *ANYKEY); fn EVP_PKEY_get1_RSA(k: *EVP_PKEY) -> *RSA;
fn EVP_PKEY_get1_RSA(k: *EVP_PKEY) -> *RSA;
fn i2d_PublicKey(k: *EVP_PKEY, buf: &*mut u8) -> c_int; fn i2d_PublicKey(k: *EVP_PKEY, buf: **mut u8) -> c_int;
fn d2i_PublicKey(t: c_int, k: &*EVP_PKEY, buf: &*u8, len: c_uint) -> *EVP_PKEY; fn d2i_PublicKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY;
fn i2d_PrivateKey(k: *EVP_PKEY, buf: &*mut u8) -> c_int; fn i2d_PrivateKey(k: *EVP_PKEY, buf: **mut u8) -> c_int;
fn d2i_PrivateKey(t: c_int, k: &*EVP_PKEY, buf: &*u8, len: c_uint) -> *EVP_PKEY; fn d2i_PrivateKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY;
fn RSA_generate_key(modsz: c_uint, e: c_uint, cb: *u8, cbarg: *u8) -> *RSA; fn RSA_generate_key(modsz: c_uint, e: c_uint, cb: *u8, cbarg: *u8) -> *RSA;
fn RSA_size(k: *RSA) -> c_uint; fn RSA_size(k: *RSA) -> c_uint;
fn RSA_public_encrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA, fn RSA_public_encrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA,
pad: c_int) -> c_int; pad: c_int) -> c_int;
fn RSA_private_decrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA, fn RSA_private_decrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA,
pad: c_int) -> c_int; pad: c_int) -> c_int;
fn RSA_sign(t: c_int, m: *u8, mlen: c_uint, sig: *mut u8, siglen: *c_uint, fn RSA_sign(t: c_int, m: *u8, mlen: c_uint, sig: *mut u8, siglen: *mut c_uint,
k: *RSA) -> c_int; k: *RSA) -> c_int;
fn RSA_verify(t: c_int, m: *u8, mlen: c_uint, sig: *u8, siglen: c_uint, fn RSA_verify(t: c_int, m: *u8, mlen: c_uint, sig: *u8, siglen: c_uint,
k: *RSA) -> c_int; k: *RSA) -> c_int;
}
} }
enum Parts { enum Parts {
@ -75,70 +79,60 @@ fn openssl_hash_nid(hash: HashType) -> c_int {
} }
} }
fn rsa_to_any(rsa: *RSA) -> *ANYKEY {
unsafe {
cast::transmute_copy(&rsa)
}
}
fn any_to_rsa(anykey: *ANYKEY) -> *RSA {
unsafe {
cast::transmute_copy(&anykey)
}
}
pub struct PKey { pub struct PKey {
priv evp: *EVP_PKEY, priv evp: *EVP_PKEY,
priv parts: Parts, priv parts: Parts,
} }
pub fn PKey() -> PKey {
unsafe {
PKey { evp: EVP_PKEY_new(), parts: Neither }
}
}
///Represents a public key, optionally with a private key attached. ///Represents a public key, optionally with a private key attached.
impl PKey { impl PKey {
unsafe fn _tostr(&self, f: extern "C" unsafe fn(*EVP_PKEY, &*mut u8) -> c_int) -> ~[u8] { pub fn new() -> PKey {
let buf = ptr::mut_null(); PKey {
let len = f(self.evp, &buf); evp: unsafe { libcrypto::EVP_PKEY_new() },
if len < 0 as c_int { return ~[]; } parts: Neither,
let mut s = vec::from_elem(len as uint, 0u8); }
let r = do s.as_mut_buf |ps, _len| {
f(self.evp, &ps)
};
s.slice(0u, r as uint).to_owned()
} }
unsafe fn _fromstr( fn _tostr(&self, f: extern "C" unsafe fn(*EVP_PKEY, **mut u8) -> c_int) -> ~[u8] {
&mut self, unsafe {
s: &[u8], let len = f(self.evp, ptr::null());
f: extern "C" unsafe fn(c_int, &*EVP_PKEY, &*u8, c_uint) -> *EVP_PKEY if len < 0 as c_int { return ~[]; }
) { let mut s = vec::from_elem(len as uint, 0u8);
let r = do s.as_mut_buf |buf, _| {
f(self.evp, &buf)
};
s.truncate(r as uint);
s
}
}
fn _fromstr(&mut self, s: &[u8], f: extern "C" unsafe fn(c_int, **EVP_PKEY, **u8, c_uint) -> *EVP_PKEY) {
do s.as_imm_buf |ps, len| { do s.as_imm_buf |ps, len| {
let evp = ptr::null(); let evp = ptr::null();
f(6 as c_int, &evp, &ps, len as c_uint); unsafe {
f(6 as c_int, &evp, &ps, len as c_uint);
}
self.evp = evp; self.evp = evp;
} }
} }
}
impl PKey {
pub fn gen(&mut self, keysz: uint) { pub fn gen(&mut self, keysz: uint) {
unsafe { unsafe {
let rsa = RSA_generate_key( let rsa = libcrypto::RSA_generate_key(
keysz as c_uint, keysz as c_uint,
65537u as c_uint, 65537u as c_uint,
ptr::null(), ptr::null(),
ptr::null() ptr::null()
); );
let rsa_ = rsa_to_any(rsa);
// XXX: 6 == NID_rsaEncryption // XXX: 6 == NID_rsaEncryption
EVP_PKEY_assign(self.evp, 6 as c_int, rsa_); libcrypto::EVP_PKEY_assign(
self.evp,
6 as c_int,
cast::transmute(rsa));
self.parts = Both; self.parts = Both;
} }
} }
@ -147,39 +141,31 @@ impl PKey {
* Returns a serialized form of the public key, suitable for load_pub(). * Returns a serialized form of the public key, suitable for load_pub().
*/ */
pub fn save_pub(&self) -> ~[u8] { pub fn save_pub(&self) -> ~[u8] {
unsafe { self._tostr(libcrypto::i2d_PublicKey)
self._tostr(i2d_PublicKey)
}
} }
/** /**
* Loads a serialized form of the public key, as produced by save_pub(). * Loads a serialized form of the public key, as produced by save_pub().
*/ */
pub fn load_pub(&mut self, s: &[u8]) { pub fn load_pub(&mut self, s: &[u8]) {
unsafe { self._fromstr(s, libcrypto::d2i_PublicKey);
self._fromstr(s, d2i_PublicKey); self.parts = Public;
self.parts = Public;
}
} }
/** /**
* Returns a serialized form of the public and private keys, suitable for * Returns a serialized form of the public and private keys, suitable for
* load_priv(). * load_priv().
*/ */
pub fn save_priv(&self, ) -> ~[u8] { pub fn save_priv(&self) -> ~[u8] {
unsafe { self._tostr(libcrypto::i2d_PrivateKey)
self._tostr(i2d_PrivateKey)
}
} }
/** /**
* Loads a serialized form of the public and private keys, as produced by * Loads a serialized form of the public and private keys, as produced by
* save_priv(). * save_priv().
*/ */
pub fn load_priv(&mut self, s: &[u8]) { pub fn load_priv(&mut self, s: &[u8]) {
unsafe { self._fromstr(s, libcrypto::d2i_PrivateKey);
self._fromstr(s, d2i_PrivateKey); self.parts = Both;
self.parts = Both;
}
} }
/** /**
@ -187,7 +173,7 @@ impl PKey {
*/ */
pub fn size(&self) -> uint { pub fn size(&self) -> uint {
unsafe { unsafe {
RSA_size(EVP_PKEY_get1_RSA(self.evp)) as uint libcrypto::RSA_size(libcrypto::EVP_PKEY_get1_RSA(self.evp)) as uint
} }
} }
@ -225,8 +211,8 @@ impl PKey {
*/ */
pub fn max_data(&self) -> uint { pub fn max_data(&self) -> uint {
unsafe { unsafe {
let rsa = EVP_PKEY_get1_RSA(self.evp); let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp);
let len = RSA_size(rsa); let len = libcrypto::RSA_size(rsa);
// 41 comes from RSA_public_encrypt(3) for OAEP // 41 comes from RSA_public_encrypt(3) for OAEP
len as uint - 41u len as uint - 41u
@ -235,8 +221,8 @@ impl PKey {
pub fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> ~[u8] { pub fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> ~[u8] {
unsafe { unsafe {
let rsa = EVP_PKEY_get1_RSA(self.evp); let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp);
let len = RSA_size(rsa); let len = libcrypto::RSA_size(rsa);
assert!(s.len() < self.max_data()); assert!(s.len() < self.max_data());
@ -244,7 +230,7 @@ impl PKey {
let rv = do r.as_mut_buf |pr, _len| { let rv = do r.as_mut_buf |pr, _len| {
do s.as_imm_buf |ps, s_len| { do s.as_imm_buf |ps, s_len| {
RSA_public_encrypt( libcrypto::RSA_public_encrypt(
s_len as c_uint, s_len as c_uint,
ps, ps,
pr, pr,
@ -256,23 +242,24 @@ impl PKey {
if rv < 0 as c_int { if rv < 0 as c_int {
~[] ~[]
} else { } else {
r.slice(0u, rv as uint).to_owned() r.truncate(rv as uint);
r
} }
} }
} }
pub fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> ~[u8] { pub fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> ~[u8] {
unsafe { unsafe {
let rsa = EVP_PKEY_get1_RSA(self.evp); let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp);
let len = RSA_size(rsa); let len = libcrypto::RSA_size(rsa);
assert!(s.len() as c_uint == RSA_size(rsa)); assert_eq!(s.len() as c_uint, libcrypto::RSA_size(rsa));
let mut r = vec::from_elem(len as uint + 1u, 0u8); let mut r = vec::from_elem(len as uint + 1u, 0u8);
let rv = do r.as_mut_buf |pr, _len| { let rv = do r.as_mut_buf |pr, _len| {
do s.as_imm_buf |ps, s_len| { do s.as_imm_buf |ps, s_len| {
RSA_private_decrypt( libcrypto::RSA_private_decrypt(
s_len as c_uint, s_len as c_uint,
ps, ps,
pr, pr,
@ -285,7 +272,8 @@ impl PKey {
if rv < 0 as c_int { if rv < 0 as c_int {
~[] ~[]
} else { } else {
r.slice(0u, rv as uint).to_owned() r.truncate(rv as uint);
r
} }
} }
} }
@ -315,18 +303,18 @@ impl PKey {
pub fn sign_with_hash(&self, s: &[u8], hash: HashType) -> ~[u8] { pub fn sign_with_hash(&self, s: &[u8], hash: HashType) -> ~[u8] {
unsafe { unsafe {
let rsa = EVP_PKEY_get1_RSA(self.evp); let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp);
let len = RSA_size(rsa); let mut len = libcrypto::RSA_size(rsa);
let mut r = vec::from_elem(len as uint + 1u, 0u8); let mut r = vec::from_elem(len as uint + 1u, 0u8);
let rv = do r.as_mut_buf |pr, _len| { let rv = do r.as_mut_buf |pr, _len| {
do s.as_imm_buf |ps, s_len| { do s.as_imm_buf |ps, s_len| {
RSA_sign( libcrypto::RSA_sign(
openssl_hash_nid(hash), openssl_hash_nid(hash),
ps, ps,
s_len as c_uint, s_len as c_uint,
pr, pr,
&len, &mut len,
rsa) rsa)
} }
}; };
@ -334,18 +322,19 @@ impl PKey {
if rv < 0 as c_int { if rv < 0 as c_int {
~[] ~[]
} else { } else {
r.slice(0u, len as uint).to_owned() r.truncate(len as uint);
r
} }
} }
} }
pub fn verify_with_hash(&self, m: &[u8], s: &[u8], hash: HashType) -> bool { pub fn verify_with_hash(&self, m: &[u8], s: &[u8], hash: HashType) -> bool {
unsafe { unsafe {
let rsa = EVP_PKEY_get1_RSA(self.evp); let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp);
do m.as_imm_buf |pm, m_len| { do m.as_imm_buf |pm, m_len| {
do s.as_imm_buf |ps, s_len| { do s.as_imm_buf |ps, s_len| {
let rv = RSA_verify( let rv = libcrypto::RSA_verify(
openssl_hash_nid(hash), openssl_hash_nid(hash),
pm, pm,
m_len as c_uint, m_len as c_uint,
@ -361,6 +350,14 @@ impl PKey {
} }
} }
impl Drop for PKey {
fn drop(&self) {
unsafe {
libcrypto::EVP_PKEY_free(self.evp);
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -368,8 +365,8 @@ mod tests {
#[test] #[test]
fn test_gen_pub() { fn test_gen_pub() {
let mut k0 = PKey(); let mut k0 = PKey::new();
let mut k1 = PKey(); let mut k1 = PKey::new();
k0.gen(512u); k0.gen(512u);
k1.load_pub(k0.save_pub()); k1.load_pub(k0.save_pub());
assert!(k0.save_pub() == k1.save_pub()); assert!(k0.save_pub() == k1.save_pub());
@ -386,8 +383,8 @@ mod tests {
#[test] #[test]
fn test_gen_priv() { fn test_gen_priv() {
let mut k0 = PKey(); let mut k0 = PKey::new();
let mut k1 = PKey(); let mut k1 = PKey::new();
k0.gen(512u); k0.gen(512u);
k1.load_priv(k0.save_priv()); k1.load_priv(k0.save_priv());
assert!(k0.save_priv() == k1.save_priv()); assert!(k0.save_priv() == k1.save_priv());
@ -404,8 +401,8 @@ mod tests {
#[test] #[test]
fn test_encrypt() { fn test_encrypt() {
let mut k0 = PKey(); let mut k0 = PKey::new();
let mut k1 = PKey(); let mut k1 = PKey::new();
let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
k0.gen(512u); k0.gen(512u);
k1.load_pub(k0.save_pub()); k1.load_pub(k0.save_pub());
@ -416,8 +413,8 @@ mod tests {
#[test] #[test]
fn test_encrypt_pkcs() { fn test_encrypt_pkcs() {
let mut k0 = PKey(); let mut k0 = PKey::new();
let mut k1 = PKey(); let mut k1 = PKey::new();
let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
k0.gen(512u); k0.gen(512u);
k1.load_pub(k0.save_pub()); k1.load_pub(k0.save_pub());
@ -428,8 +425,8 @@ mod tests {
#[test] #[test]
fn test_sign() { fn test_sign() {
let mut k0 = PKey(); let mut k0 = PKey::new();
let mut k1 = PKey(); let mut k1 = PKey::new();
let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
k0.gen(512u); k0.gen(512u);
k1.load_pub(k0.save_pub()); k1.load_pub(k0.save_pub());
@ -440,8 +437,8 @@ mod tests {
#[test] #[test]
fn test_sign_hashes() { fn test_sign_hashes() {
let mut k0 = PKey(); let mut k0 = PKey::new();
let mut k1 = PKey(); let mut k1 = PKey::new();
let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8];
k0.gen(512u); k0.gen(512u);
k1.load_pub(k0.save_pub()); k1.load_pub(k0.save_pub());
@ -451,5 +448,4 @@ mod tests {
assert!(k1.verify_with_hash(msg, sig, MD5)); assert!(k1.verify_with_hash(msg, sig, MD5));
assert!(!k1.verify_with_hash(msg, sig, SHA1)); assert!(!k1.verify_with_hash(msg, sig, SHA1));
} }
} }

17
rand.rs
View File

@ -1,20 +1,21 @@
use std::libc::c_int; use std::libc::c_int;
use std::vec; use std::vec;
#[link_args = "-lcrypto"] mod libcrypto {
#[abi = "cdecl"] use std::libc::c_int;
extern {
fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int; #[link_args = "-lcrypto"]
extern {
fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int;
}
} }
pub fn rand_bytes(len: uint) -> ~[u8] { pub fn rand_bytes(len: uint) -> ~[u8] {
let mut out = vec::with_capacity(len); let mut out = vec::with_capacity(len);
do out.as_mut_buf |out_buf, len| { do out.as_mut_buf |out_buf, len| {
unsafe { let r = unsafe { libcrypto::RAND_bytes(out_buf, len as c_int) };
let r = RAND_bytes(out_buf, len as c_int); if r != 1 as c_int { fail!() }
if r != 1 as c_int { fail!() }
}
} }
unsafe { vec::raw::set_len(&mut out, len); } unsafe { vec::raw::set_len(&mut out, len); }

111
symm.rs
View File

@ -1,35 +1,41 @@
use std::libc::{c_int, c_uint}; use std::libc::c_int;
use std::{libc,vec}; use std::libc;
use std::vec;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
type EVP_CIPHER_CTX = *libc::c_void; pub type EVP_CIPHER_CTX = *libc::c_void;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
type EVP_CIPHER = *libc::c_void; pub type EVP_CIPHER = *libc::c_void;
#[link_args = "-lcrypto"] mod libcrypto {
#[abi = "cdecl"] use super::*;
extern { use std::libc::{c_int, c_uint};
fn EVP_CIPHER_CTX_new() -> EVP_CIPHER_CTX;
fn EVP_CIPHER_CTX_set_padding(ctx: EVP_CIPHER_CTX, padding: c_int);
fn EVP_aes_128_ecb() -> EVP_CIPHER; extern {
fn EVP_aes_128_cbc() -> EVP_CIPHER; #[link_args = "-lcrypto"]
// fn EVP_aes_128_ctr() -> EVP_CIPHER; fn EVP_CIPHER_CTX_new() -> EVP_CIPHER_CTX;
// fn EVP_aes_128_gcm() -> EVP_CIPHER; fn EVP_CIPHER_CTX_set_padding(ctx: EVP_CIPHER_CTX, padding: c_int);
fn EVP_CIPHER_CTX_free(ctx: EVP_CIPHER_CTX);
fn EVP_aes_256_ecb() -> EVP_CIPHER; fn EVP_aes_128_ecb() -> EVP_CIPHER;
fn EVP_aes_256_cbc() -> EVP_CIPHER; fn EVP_aes_128_cbc() -> EVP_CIPHER;
// fn EVP_aes_256_ctr() -> EVP_CIPHER; // fn EVP_aes_128_ctr() -> EVP_CIPHER;
// fn EVP_aes_256_gcm() -> EVP_CIPHER; // fn EVP_aes_128_gcm() -> EVP_CIPHER;
fn EVP_rc4() -> EVP_CIPHER; fn EVP_aes_256_ecb() -> EVP_CIPHER;
fn EVP_aes_256_cbc() -> EVP_CIPHER;
// fn EVP_aes_256_ctr() -> EVP_CIPHER;
// fn EVP_aes_256_gcm() -> EVP_CIPHER;
fn EVP_CipherInit(ctx: EVP_CIPHER_CTX, evp: EVP_CIPHER, fn EVP_rc4() -> EVP_CIPHER;
key: *u8, iv: *u8, mode: c_int);
fn EVP_CipherUpdate(ctx: EVP_CIPHER_CTX, outbuf: *mut u8, fn EVP_CipherInit(ctx: EVP_CIPHER_CTX, evp: EVP_CIPHER,
outlen: &mut c_uint, inbuf: *u8, inlen: c_int); key: *u8, iv: *u8, mode: c_int);
fn EVP_CipherFinal(ctx: EVP_CIPHER_CTX, res: *mut u8, len: &mut c_int); fn EVP_CipherUpdate(ctx: EVP_CIPHER_CTX, outbuf: *mut u8,
outlen: &mut c_uint, inbuf: *u8, inlen: c_int);
fn EVP_CipherFinal(ctx: EVP_CIPHER_CTX, res: *mut u8, len: &mut c_int);
}
} }
pub enum Mode { pub enum Mode {
@ -55,17 +61,17 @@ pub enum Type {
fn evpc(t: Type) -> (EVP_CIPHER, uint, uint) { fn evpc(t: Type) -> (EVP_CIPHER, uint, uint) {
unsafe { unsafe {
match t { match t {
AES_128_ECB => (EVP_aes_128_ecb(), 16u, 16u), AES_128_ECB => (libcrypto::EVP_aes_128_ecb(), 16u, 16u),
AES_128_CBC => (EVP_aes_128_cbc(), 16u, 16u), AES_128_CBC => (libcrypto::EVP_aes_128_cbc(), 16u, 16u),
// AES_128_CTR => (EVP_aes_128_ctr(), 16u, 0u), // AES_128_CTR => (libcrypto::EVP_aes_128_ctr(), 16u, 0u),
//AES_128_GCM => (EVP_aes_128_gcm(), 16u, 16u), //AES_128_GCM => (libcrypto::EVP_aes_128_gcm(), 16u, 16u),
AES_256_ECB => (EVP_aes_256_ecb(), 32u, 16u), AES_256_ECB => (libcrypto::EVP_aes_256_ecb(), 32u, 16u),
AES_256_CBC => (EVP_aes_256_cbc(), 32u, 16u), AES_256_CBC => (libcrypto::EVP_aes_256_cbc(), 32u, 16u),
// AES_256_CTR => (EVP_aes_256_ctr(), 32u, 0u), // AES_256_CTR => (libcrypto::EVP_aes_256_ctr(), 32u, 0u),
//AES_256_GCM => (EVP_aes_256_gcm(), 32u, 16u), //AES_256_GCM => (libcrypto::EVP_aes_256_gcm(), 32u, 16u),
RC4_128 => (EVP_rc4(), 16u, 0u), RC4_128 => (libcrypto::EVP_rc4(), 16u, 0u),
} }
} }
} }
@ -78,15 +84,13 @@ pub struct Crypter {
priv blocksize: uint priv blocksize: uint
} }
pub fn Crypter(t: Type) -> Crypter { impl Crypter {
unsafe { pub fn new(t: Type) -> Crypter {
let ctx = EVP_CIPHER_CTX_new(); let ctx = unsafe { libcrypto::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 }
} }
}
impl Crypter {
/** /**
* Enables or disables padding. If padding is disabled, total amount of * Enables or disables padding. If padding is disabled, total amount of
* data encrypted must be a multiple of block size. * data encrypted must be a multiple of block size.
@ -95,7 +99,7 @@ impl Crypter {
if self.blocksize > 0 { if self.blocksize > 0 {
unsafe { unsafe {
let v = if padding { 1 } else { 0 } as c_int; let v = if padding { 1 } else { 0 } as c_int;
EVP_CIPHER_CTX_set_padding(self.ctx, v); libcrypto::EVP_CIPHER_CTX_set_padding(self.ctx, v);
} }
} }
} }
@ -109,11 +113,11 @@ impl Crypter {
Encrypt => 1 as c_int, Encrypt => 1 as c_int,
Decrypt => 0 as c_int, Decrypt => 0 as c_int,
}; };
assert!(key.len() == self.keylen); assert_eq!(key.len(), self.keylen);
do key.as_imm_buf |pkey, _len| { do key.as_imm_buf |pkey, _len| {
do iv.as_imm_buf |piv, _len| { do iv.as_imm_buf |piv, _len| {
EVP_CipherInit( libcrypto::EVP_CipherInit(
self.ctx, self.ctx,
self.evp, self.evp,
pkey, pkey,
@ -137,7 +141,7 @@ impl Crypter {
let reslen = do res.as_mut_buf |pres, _len| { let reslen = do res.as_mut_buf |pres, _len| {
let mut reslen = (len + self.blocksize) as u32; let mut reslen = (len + self.blocksize) as u32;
EVP_CipherUpdate( libcrypto::EVP_CipherUpdate(
self.ctx, self.ctx,
pres, pres,
&mut reslen, &mut reslen,
@ -148,7 +152,8 @@ impl Crypter {
reslen reslen
}; };
res.slice(0u, reslen as uint).to_owned() res.truncate(reslen as uint);
res
} }
} }
} }
@ -162,11 +167,20 @@ impl Crypter {
let reslen = do res.as_mut_buf |pres, _len| { let reslen = do res.as_mut_buf |pres, _len| {
let mut reslen = self.blocksize as c_int; let mut reslen = self.blocksize as c_int;
EVP_CipherFinal(self.ctx, pres, &mut reslen); libcrypto::EVP_CipherFinal(self.ctx, pres, &mut reslen);
reslen reslen
}; };
res.slice(0u, reslen as uint).to_owned() res.truncate(reslen as uint);
res
}
}
}
impl Drop for Crypter {
fn drop(&self) {
unsafe {
libcrypto::EVP_CIPHER_CTX_free(self.ctx);
} }
} }
} }
@ -176,7 +190,7 @@ impl Crypter {
* specified key and iv; returns the resulting (encrypted) data. * specified key and iv; returns the resulting (encrypted) data.
*/ */
pub fn encrypt(t: Type, key: &[u8], iv: ~[u8], data: &[u8]) -> ~[u8] { pub fn encrypt(t: Type, key: &[u8], iv: ~[u8], data: &[u8]) -> ~[u8] {
let c = Crypter(t); let c = Crypter::new(t);
c.init(Encrypt, key, iv); c.init(Encrypt, key, iv);
let r = c.update(data); let r = c.update(data);
let rest = c.final(); let rest = c.final();
@ -188,7 +202,7 @@ pub fn encrypt(t: Type, key: &[u8], iv: ~[u8], data: &[u8]) -> ~[u8] {
* specified key and iv; returns the resulting (decrypted) data. * specified key and iv; returns the resulting (decrypted) data.
*/ */
pub fn decrypt(t: Type, key: &[u8], iv: ~[u8], data: &[u8]) -> ~[u8] { pub fn decrypt(t: Type, key: &[u8], iv: ~[u8], data: &[u8]) -> ~[u8] {
let c = Crypter(t); let c = Crypter::new(t);
c.init(Decrypt, key, iv); c.init(Decrypt, key, iv);
let r = c.update(data); let r = c.update(data);
let rest = c.final(); let rest = c.final();
@ -216,7 +230,7 @@ mod tests {
let c0 = let c0 =
~[ 0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8, ~[ 0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8,
0xeau8, 0xfcu8, 0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8 ]; 0xeau8, 0xfcu8, 0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8 ];
let c = Crypter(AES_256_ECB); let c = Crypter::new(AES_256_ECB);
c.init(Encrypt, k0, []); c.init(Encrypt, k0, []);
c.pad(false); c.pad(false);
let r0 = c.update(p0) + c.final(); let r0 = c.update(p0) + c.final();
@ -230,7 +244,7 @@ mod tests {
fn cipher_test(ciphertype: Type, pt: ~str, ct: ~str, key: ~str, iv: ~str) { fn cipher_test(ciphertype: Type, pt: ~str, ct: ~str, key: ~str, iv: ~str) {
use hex::ToHex; use hex::ToHex;
let cipher = Crypter(ciphertype); let cipher = Crypter::new(ciphertype);
cipher.init(Encrypt, key.from_hex(), iv.from_hex()); cipher.init(Encrypt, key.from_hex(), iv.from_hex());
let expected = ct.from_hex(); let expected = ct.from_hex();
@ -279,5 +293,4 @@ mod tests {
cipher_test(AES_128_GCM, pt, ct, key, iv); cipher_test(AES_128_GCM, pt, ct, key, iv);
}*/ }*/
} }