update to rust 0.9-pre (a5fa1d9)

This commit is contained in:
Erick Tryzelaar 2013-12-27 22:02:38 -05:00
parent a9ce2a36d5
commit 85e6d1db12
10 changed files with 268 additions and 355 deletions

2
.gitignore vendored
View File

@ -6,4 +6,4 @@
/bin/ /bin/
/build/ /build/
/lib/ /lib/
/src/crypto/lib /src/crypto/crypto

View File

@ -7,7 +7,7 @@ all:
test: test:
$(RUSTC) $(RUST_FLAGS) --test src/crypto/lib.rs $(RUSTC) $(RUST_FLAGS) --test src/crypto/lib.rs
./src/crypto/lib ./src/crypto/crypto
clean: clean:
rm -rf bin/ lib/ build/ src/crypto/lib rm -rf bin/ lib/ build/ src/crypto/lib

View File

@ -18,37 +18,32 @@ 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;
mod libcrypto { #[link(name = "crypto")]
use super::*; extern {
use std::libc::c_uint; fn EVP_MD_CTX_create() -> EVP_MD_CTX;
fn EVP_MD_CTX_destroy(ctx: EVP_MD_CTX);
#[link(name = "crypto")] fn EVP_md5() -> EVP_MD;
extern { fn EVP_sha1() -> EVP_MD;
pub fn EVP_MD_CTX_create() -> EVP_MD_CTX; fn EVP_sha224() -> EVP_MD;
pub fn EVP_MD_CTX_destroy(ctx: EVP_MD_CTX); fn EVP_sha256() -> EVP_MD;
fn EVP_sha384() -> EVP_MD;
fn EVP_sha512() -> EVP_MD;
pub fn EVP_md5() -> EVP_MD; fn EVP_DigestInit(ctx: EVP_MD_CTX, typ: EVP_MD);
pub fn EVP_sha1() -> EVP_MD; fn EVP_DigestUpdate(ctx: EVP_MD_CTX, data: *u8, n: c_uint);
pub fn EVP_sha224() -> EVP_MD; fn EVP_DigestFinal(ctx: EVP_MD_CTX, res: *mut u8, n: *u32);
pub fn EVP_sha256() -> EVP_MD;
pub fn EVP_sha384() -> EVP_MD;
pub fn EVP_sha512() -> EVP_MD;
pub fn EVP_DigestInit(ctx: EVP_MD_CTX, typ: EVP_MD);
pub fn EVP_DigestUpdate(ctx: EVP_MD_CTX, data: *u8, n: c_uint);
pub 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 => (libcrypto::EVP_md5(), 16u), MD5 => (EVP_md5(), 16u),
SHA1 => (libcrypto::EVP_sha1(), 20u), SHA1 => (EVP_sha1(), 20u),
SHA224 => (libcrypto::EVP_sha224(), 28u), SHA224 => (EVP_sha224(), 28u),
SHA256 => (libcrypto::EVP_sha256(), 32u), SHA256 => (EVP_sha256(), 32u),
SHA384 => (libcrypto::EVP_sha384(), 48u), SHA384 => (EVP_sha384(), 48u),
SHA512 => (libcrypto::EVP_sha512(), 64u), SHA512 => (EVP_sha512(), 64u),
} }
} }
} }
@ -61,10 +56,10 @@ pub struct Hasher {
impl Hasher { impl Hasher {
pub fn new(ht: HashType) -> Hasher { pub fn new(ht: HashType) -> Hasher {
let ctx = unsafe { libcrypto::EVP_MD_CTX_create() }; let ctx = unsafe { EVP_MD_CTX_create() };
let (evp, mdlen) = evpmd(ht); let (evp, mdlen) = evpmd(ht);
unsafe { unsafe {
libcrypto::EVP_DigestInit(ctx, evp); EVP_DigestInit(ctx, evp);
} }
Hasher { evp: evp, ctx: ctx, len: mdlen } Hasher { evp: evp, ctx: ctx, len: mdlen }
@ -72,11 +67,9 @@ impl Hasher {
/// 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]) {
data.as_imm_buf(|pdata, len| { unsafe {
unsafe { EVP_DigestUpdate(self.ctx, data.as_ptr(), data.len() as c_uint)
libcrypto::EVP_DigestUpdate(self.ctx, pdata, len as c_uint) }
}
});
} }
/** /**
@ -84,20 +77,18 @@ impl Hasher {
* initialization * initialization
*/ */
pub fn final(&self) -> ~[u8] { pub fn final(&self) -> ~[u8] {
let mut res = vec::from_elem(self.len, 0u8); unsafe {
res.as_mut_buf(|pres, _len| { let mut res = vec::from_elem(self.len, 0u8);
unsafe { EVP_DigestFinal(self.ctx, res.as_mut_ptr(), ptr::null());
libcrypto::EVP_DigestFinal(self.ctx, pres, ptr::null()); res
} }
});
res
} }
} }
impl Drop for Hasher { impl Drop for Hasher {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
libcrypto::EVP_MD_CTX_destroy(self.ctx); EVP_MD_CTX_destroy(self.ctx);
} }
} }
} }
@ -114,7 +105,6 @@ pub fn hash(t: HashType, data: &[u8]) -> ~[u8] {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use hex::FromHex; use hex::FromHex;
use hex::ToHex; use hex::ToHex;
@ -128,8 +118,8 @@ mod tests {
expected_output: output } expected_output: output }
} }
fn hash_test(hashtype: HashType, hashtest: &HashTest) { fn hash_test(hashtype: super::HashType, hashtest: &HashTest) {
let calced_raw = hash(hashtype, hashtest.input); let calced_raw = super::hash(hashtype, hashtest.input);
let calced = calced_raw.to_hex(); let calced = calced_raw.to_hex();
@ -159,7 +149,7 @@ mod tests {
HashTest(~"AAED18DBE8938C19ED734A8D", ~"6F80FB775F27E0A4CE5C2F42FC72C5F1")]; HashTest(~"AAED18DBE8938C19ED734A8D", ~"6F80FB775F27E0A4CE5C2F42FC72C5F1")];
for test in tests.iter() { for test in tests.iter() {
hash_test(MD5, test); hash_test(super::MD5, test);
} }
} }
@ -170,7 +160,7 @@ mod tests {
]; ];
for test in tests.iter() { for test in tests.iter() {
hash_test(SHA1, test); hash_test(super::SHA1, test);
} }
} }
@ -181,7 +171,7 @@ mod tests {
]; ];
for test in tests.iter() { for test in tests.iter() {
hash_test(SHA256, test); hash_test(super::SHA256, test);
} }
} }
} }

View File

@ -71,17 +71,12 @@ impl<'a> FromHex for &'a str {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
#[test] #[test]
pub fn test() { pub fn test() {
assert!([05u8, 0xffu8, 0x00u8, 0x59u8].to_hex() == ~"05FF0059"); assert!([05u8, 0xffu8, 0x00u8, 0x59u8].to_hex() == ~"05FF0059");
assert!("00FFA9D1F5".from_hex() == ~[0, 0xff, 0xa9, 0xd1, 0xf5]); assert!("00FFA9D1F5".from_hex() == ~[0, 0xff, 0xa9, 0xd1, 0xf5]);
assert!("00FFA9D1F5".from_hex().to_hex() == ~"00FFA9D1F5"); assert!("00FFA9D1F5".from_hex().to_hex() == ~"00FFA9D1F5");
} }
} }

View File

@ -14,26 +14,26 @@
* limitations under the License. * limitations under the License.
*/ */
use hash::*; use std::libc::{c_uchar, c_int, c_uint};
use std::{libc,ptr,vec}; use std::ptr;
use std::vec;
use hash;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
pub struct HMAC_CTX { pub struct HMAC_CTX {
md: EVP_MD, md: hash::EVP_MD,
md_ctx: EVP_MD_CTX, md_ctx: hash::EVP_MD_CTX,
i_ctx: EVP_MD_CTX, i_ctx: hash::EVP_MD_CTX,
o_ctx: EVP_MD_CTX, o_ctx: hash::EVP_MD_CTX,
key_length: libc::c_uint, key_length: c_uint,
key: [libc::c_uchar, ..128] key: [c_uchar, ..128]
} }
#[link(name = "crypto")] #[link(name = "crypto")]
extern { extern {
fn HMAC_CTX_init(ctx: *mut HMAC_CTX, key: *u8, keylen: libc::c_int, md: EVP_MD); fn HMAC_CTX_init(ctx: *mut HMAC_CTX, key: *u8, keylen: c_int, md: hash::EVP_MD);
fn HMAC_Update(ctx: *mut HMAC_CTX, input: *u8, len: c_uint);
fn HMAC_Update(ctx: *mut HMAC_CTX, input: *u8, len: libc::c_uint); fn HMAC_Final(ctx: *mut HMAC_CTX, output: *mut u8, len: *mut c_uint);
fn HMAC_Final(ctx: *mut HMAC_CTX, output: *mut u8, len: *mut libc::c_uint);
} }
pub struct HMAC { pub struct HMAC {
@ -41,10 +41,9 @@ pub struct HMAC {
priv len: uint, priv len: uint,
} }
pub fn HMAC(ht: HashType, key: ~[u8]) -> HMAC { pub fn HMAC(ht: hash::HashType, key: ~[u8]) -> HMAC {
unsafe { unsafe {
let (evp, mdlen) = hash::evpmd(ht);
let (evp, mdlen) = evpmd(ht);
let mut ctx : HMAC_CTX = HMAC_CTX { let mut ctx : HMAC_CTX = HMAC_CTX {
md: ptr::null(), md: ptr::null(),
@ -57,7 +56,7 @@ pub fn HMAC(ht: HashType, key: ~[u8]) -> HMAC {
HMAC_CTX_init(&mut ctx, HMAC_CTX_init(&mut ctx,
key.as_ptr(), key.as_ptr(),
key.len() as libc::c_int, key.len() as c_int,
evp); evp);
HMAC { ctx: ctx, len: mdlen } HMAC { ctx: ctx, len: mdlen }
@ -67,20 +66,16 @@ pub fn HMAC(ht: HashType, key: ~[u8]) -> HMAC {
impl HMAC { impl HMAC {
pub fn update(&mut self, data: &[u8]) { pub fn update(&mut self, data: &[u8]) {
unsafe { unsafe {
data.as_imm_buf(|pdata, len| { HMAC_Update(&mut self.ctx, data.as_ptr(), data.len() as c_uint)
HMAC_Update(&mut self.ctx, pdata, len as libc::c_uint)
});
} }
} }
pub fn final(&mut self) -> ~[u8] { pub fn final(&mut self) -> ~[u8] {
unsafe { unsafe {
let mut res = vec::from_elem(self.len, 0u8); let mut res = vec::from_elem(self.len, 0u8);
let mut outlen: libc::c_uint = 0; let mut outlen = 0;
res.as_mut_buf(|pres, _len| { HMAC_Final(&mut self.ctx, res.as_mut_ptr(), &mut outlen);
HMAC_Final(&mut self.ctx, pres, &mut outlen); assert!(self.len == outlen as uint)
assert!(self.len == outlen as uint)
});
res res
} }
} }

View File

@ -15,13 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
#[link(name = "crypto", #[crate_id = "crypto#0.3"];
package_id = "crypto",
vers = "0.3",
uuid = "38297409-b4c2-4499-8131-a99a7e44dad3")];
#[crate_type = "lib"];
#[feature(globs)];
pub mod hash; pub mod hash;
pub mod hex; pub mod hex;

View File

@ -1,57 +1,44 @@
use std::libc::c_int; use std::libc::c_int;
use std::vec; use std::vec;
mod libcrypto { #[link(name = "crypto")]
use std::libc::c_int; extern {
fn PKCS5_PBKDF2_HMAC_SHA1(pass: *u8, passlen: c_int,
#[link(name = "crypto")] salt: *u8, saltlen: c_int,
extern { iter: c_int, keylen: c_int,
pub 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;
}
} }
/// Derives a key from a password and salt using the PBKDF2-HMAC-SHA1 algorithm. /// Derives a key from a password and salt using the PBKDF2-HMAC-SHA1 algorithm.
pub fn pbkdf2_hmac_sha1(pass: &str, salt: &[u8], iter: uint, pub fn pbkdf2_hmac_sha1(pass: &str, salt: &[u8], iter: uint, keylen: uint) -> ~[u8] {
keylen: uint) -> ~[u8] { unsafe {
assert!(iter >= 1u); assert!(iter >= 1);
assert!(keylen >= 1u); assert!(keylen >= 1);
pass.as_imm_buf(|pass_buf, pass_len| { let mut out = vec::with_capacity(keylen);
salt.as_imm_buf(|salt_buf, salt_len| {
let mut out = vec::with_capacity(keylen);
out.as_mut_buf(|out_buf, _out_len| { let r = PKCS5_PBKDF2_HMAC_SHA1(
let r = unsafe { pass.as_ptr(), pass.len() as c_int,
libcrypto::PKCS5_PBKDF2_HMAC_SHA1( salt.as_ptr(), salt.len() as c_int,
pass_buf, pass_len as c_int, iter as c_int, keylen as c_int,
salt_buf, salt_len as c_int, out.as_mut_ptr());
iter as c_int, keylen as c_int,
out_buf)
};
if r != 1 as c_int { fail!(); } if r != 1 { fail!(); }
});
unsafe { out.set_len(keylen); } out.set_len(keylen);
out out
}) }
})
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
// Test vectors from // Test vectors from
// 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!(
pbkdf2_hmac_sha1( super::pbkdf2_hmac_sha1(
"password", "password",
"salt".as_bytes(), "salt".as_bytes(),
1u, 1u,
@ -65,7 +52,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
pbkdf2_hmac_sha1( super::pbkdf2_hmac_sha1(
"password", "password",
"salt".as_bytes(), "salt".as_bytes(),
2u, 2u,
@ -79,7 +66,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
pbkdf2_hmac_sha1( super::pbkdf2_hmac_sha1(
"password", "password",
"salt".as_bytes(), "salt".as_bytes(),
4096u, 4096u,
@ -93,7 +80,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
pbkdf2_hmac_sha1( super::pbkdf2_hmac_sha1(
"password", "password",
"salt".as_bytes(), "salt".as_bytes(),
16777216u, 16777216u,
@ -107,7 +94,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
pbkdf2_hmac_sha1( super::pbkdf2_hmac_sha1(
"passwordPASSWORDpassword", "passwordPASSWORDpassword",
"saltSALTsaltSALTsaltSALTsaltSALTsalt".as_bytes(), "saltSALTsaltSALTsaltSALTsaltSALTsalt".as_bytes(),
4096u, 4096u,
@ -122,7 +109,7 @@ mod tests {
); );
assert_eq!( assert_eq!(
pbkdf2_hmac_sha1( super::pbkdf2_hmac_sha1(
"pass\x00word", "pass\x00word",
"sa\x00lt".as_bytes(), "sa\x00lt".as_bytes(),
4096u, 4096u,

View File

@ -1,5 +1,5 @@
use std::cast; use std::cast;
use std::libc::{c_int, c_uint}; use std::libc::{c_char, c_int, c_uint};
use std::libc; use std::libc;
use std::ptr; use std::ptr;
use std::vec; use std::vec;
@ -11,34 +11,29 @@ pub type EVP_PKEY = *libc::c_void;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
pub type RSA = *libc::c_void; pub type RSA = *libc::c_void;
mod libcrypto { #[link(name = "crypto")]
use super::*; extern {
use std::libc::{c_char, c_int, c_uint}; fn EVP_PKEY_new() -> *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_get1_RSA(k: *EVP_PKEY) -> *RSA;
#[link(name = "crypto")] fn i2d_PublicKey(k: *EVP_PKEY, buf: **mut u8) -> c_int;
extern { fn d2i_PublicKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY;
pub fn EVP_PKEY_new() -> *EVP_PKEY; fn i2d_PrivateKey(k: *EVP_PKEY, buf: **mut u8) -> c_int;
pub fn EVP_PKEY_free(k: *EVP_PKEY); fn d2i_PrivateKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY;
pub fn EVP_PKEY_assign(pkey: *EVP_PKEY, typ: c_int, key: *c_char) -> c_int;
pub fn EVP_PKEY_get1_RSA(k: *EVP_PKEY) -> *RSA;
pub fn i2d_PublicKey(k: *EVP_PKEY, buf: **mut u8) -> c_int; fn RSA_generate_key(modsz: c_uint, e: c_uint, cb: *u8, cbarg: *u8) -> *RSA;
pub fn d2i_PublicKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY; fn RSA_size(k: *RSA) -> c_uint;
pub fn i2d_PrivateKey(k: *EVP_PKEY, buf: **mut u8) -> c_int;
pub fn d2i_PrivateKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY;
pub fn RSA_generate_key(modsz: c_uint, e: c_uint, cb: *u8, cbarg: *u8) -> *RSA; fn RSA_public_encrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA,
pub fn RSA_size(k: *RSA) -> c_uint; pad: c_int) -> c_int;
fn RSA_private_decrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA,
pub 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_sign(t: c_int, m: *u8, mlen: c_uint, sig: *mut u8, siglen: *mut c_uint,
pub fn RSA_private_decrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA, k: *RSA) -> c_int;
pad: c_int) -> c_int; fn RSA_verify(t: c_int, m: *u8, mlen: c_uint, sig: *u8, siglen: c_uint,
pub 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;
pub fn RSA_verify(t: c_int, m: *u8, mlen: c_uint, sig: *u8, siglen: c_uint,
k: *RSA) -> c_int;
}
} }
enum Parts { enum Parts {
@ -87,9 +82,11 @@ pub struct PKey {
/// Represents a public key, optionally with a private key attached. /// Represents a public key, optionally with a private key attached.
impl PKey { impl PKey {
pub fn new() -> PKey { pub fn new() -> PKey {
PKey { unsafe {
evp: unsafe { libcrypto::EVP_PKEY_new() }, PKey {
parts: Neither, evp: EVP_PKEY_new(),
parts: Neither,
}
} }
} }
@ -99,9 +96,7 @@ impl PKey {
if len < 0 as c_int { return ~[]; } if len < 0 as c_int { return ~[]; }
let mut s = vec::from_elem(len as uint, 0u8); let mut s = vec::from_elem(len as uint, 0u8);
let r = s.as_mut_buf(|buf, _| { let r = f(self.evp, &s.as_mut_ptr());
f(self.evp, &buf)
});
s.truncate(r as uint); s.truncate(r as uint);
s s
@ -109,18 +104,16 @@ impl PKey {
} }
fn _fromstr(&mut self, s: &[u8], f: extern "C" unsafe fn(c_int, **EVP_PKEY, **u8, c_uint) -> *EVP_PKEY) { fn _fromstr(&mut self, s: &[u8], f: extern "C" unsafe fn(c_int, **EVP_PKEY, **u8, c_uint) -> *EVP_PKEY) {
s.as_imm_buf(|ps, len| { unsafe {
let evp = ptr::null(); let evp = ptr::null();
unsafe { f(6 as c_int, &evp, &s.as_ptr(), s.len() as c_uint);
f(6 as c_int, &evp, &ps, len as c_uint);
}
self.evp = evp; self.evp = evp;
}); }
} }
pub fn gen(&mut self, keysz: uint) { pub fn gen(&mut self, keysz: uint) {
unsafe { unsafe {
let rsa = libcrypto::RSA_generate_key( let rsa = RSA_generate_key(
keysz as c_uint, keysz as c_uint,
65537u as c_uint, 65537u as c_uint,
ptr::null(), ptr::null(),
@ -128,7 +121,7 @@ impl PKey {
); );
// XXX: 6 == NID_rsaEncryption // XXX: 6 == NID_rsaEncryption
libcrypto::EVP_PKEY_assign( EVP_PKEY_assign(
self.evp, self.evp,
6 as c_int, 6 as c_int,
cast::transmute(rsa)); cast::transmute(rsa));
@ -141,14 +134,14 @@ 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] {
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]) {
self._fromstr(s, libcrypto::d2i_PublicKey); self._fromstr(s, d2i_PublicKey);
self.parts = Public; self.parts = Public;
} }
@ -157,14 +150,14 @@ impl PKey {
* load_priv(). * load_priv().
*/ */
pub fn save_priv(&self) -> ~[u8] { pub fn save_priv(&self) -> ~[u8] {
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]) {
self._fromstr(s, libcrypto::d2i_PrivateKey); self._fromstr(s, d2i_PrivateKey);
self.parts = Both; self.parts = Both;
} }
@ -173,7 +166,7 @@ impl PKey {
*/ */
pub fn size(&self) -> uint { pub fn size(&self) -> uint {
unsafe { unsafe {
libcrypto::RSA_size(libcrypto::EVP_PKEY_get1_RSA(self.evp)) as uint RSA_size(EVP_PKEY_get1_RSA(self.evp)) as uint
} }
} }
@ -211,8 +204,8 @@ impl PKey {
*/ */
pub fn max_data(&self) -> uint { pub fn max_data(&self) -> uint {
unsafe { unsafe {
let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let rsa = EVP_PKEY_get1_RSA(self.evp);
let len = libcrypto::RSA_size(rsa); let len = 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
@ -221,24 +214,20 @@ 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 = libcrypto::EVP_PKEY_get1_RSA(self.evp); let rsa = EVP_PKEY_get1_RSA(self.evp);
let len = libcrypto::RSA_size(rsa); let len = RSA_size(rsa);
assert!(s.len() < self.max_data()); assert!(s.len() < self.max_data());
let mut r = vec::from_elem(len as uint + 1u, 0u8); let mut r = vec::from_elem(len as uint + 1u, 0u8);
let rv = r.as_mut_buf(|pr, _len| { let rv = RSA_public_encrypt(
s.as_imm_buf(|ps, s_len| { s.len() as c_uint,
libcrypto::RSA_public_encrypt( s.as_ptr(),
s_len as c_uint, r.as_mut_ptr(),
ps, rsa,
pr, openssl_padding_code(padding));
rsa,
openssl_padding_code(padding)
)
})
});
if rv < 0 as c_int { if rv < 0 as c_int {
~[] ~[]
} else { } else {
@ -250,24 +239,19 @@ impl PKey {
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 = libcrypto::EVP_PKEY_get1_RSA(self.evp); let rsa = EVP_PKEY_get1_RSA(self.evp);
let len = libcrypto::RSA_size(rsa); let len = RSA_size(rsa);
assert_eq!(s.len() as c_uint, libcrypto::RSA_size(rsa)); assert_eq!(s.len() as c_uint, 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 = r.as_mut_buf(|pr, _len| { let rv = RSA_private_decrypt(
s.as_imm_buf(|ps, s_len| { s.len() as c_uint,
libcrypto::RSA_private_decrypt( s.as_ptr(),
s_len as c_uint, r.as_mut_ptr(),
ps, rsa,
pr, openssl_padding_code(padding));
rsa,
openssl_padding_code(padding)
)
})
});
if rv < 0 as c_int { if rv < 0 as c_int {
~[] ~[]
@ -303,21 +287,17 @@ 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 = libcrypto::EVP_PKEY_get1_RSA(self.evp); let rsa = EVP_PKEY_get1_RSA(self.evp);
let mut len = libcrypto::RSA_size(rsa); let mut len = 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 = r.as_mut_buf(|pr, _len| { let rv = RSA_sign(
s.as_imm_buf(|ps, s_len| { openssl_hash_nid(hash),
libcrypto::RSA_sign( s.as_ptr(),
openssl_hash_nid(hash), s.len() as c_uint,
ps, r.as_mut_ptr(),
s_len as c_uint, &mut len,
pr, rsa);
&mut len,
rsa)
})
});
if rv < 0 as c_int { if rv < 0 as c_int {
~[] ~[]
@ -330,22 +310,18 @@ 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: HashType) -> bool {
unsafe { unsafe {
let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let rsa = EVP_PKEY_get1_RSA(self.evp);
m.as_imm_buf(|pm, m_len| { let rv = RSA_verify(
s.as_imm_buf(|ps, s_len| { openssl_hash_nid(hash),
let rv = libcrypto::RSA_verify( m.as_ptr(),
openssl_hash_nid(hash), m.len() as c_uint,
pm, s.as_ptr(),
m_len as c_uint, s.len() as c_uint,
ps, rsa
s_len as c_uint, );
rsa
);
rv == 1 as c_int rv == 1 as c_int
})
})
} }
} }
} }
@ -353,56 +329,55 @@ impl PKey {
impl Drop for PKey { impl Drop for PKey {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
libcrypto::EVP_PKEY_free(self.evp); EVP_PKEY_free(self.evp);
} }
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use hash::{MD5, SHA1}; use hash::{MD5, SHA1};
#[test] #[test]
fn test_gen_pub() { fn test_gen_pub() {
let mut k0 = PKey::new(); let mut k0 = super::PKey::new();
let mut k1 = PKey::new(); let mut k1 = super::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_eq!(k0.save_pub(), k1.save_pub());
assert!(k0.size() == k1.size()); assert_eq!(k0.size(), k1.size());
assert!(k0.can(Encrypt)); assert!(k0.can(super::Encrypt));
assert!(k0.can(Decrypt)); assert!(k0.can(super::Decrypt));
assert!(k0.can(Verify)); assert!(k0.can(super::Verify));
assert!(k0.can(Sign)); assert!(k0.can(super::Sign));
assert!(k1.can(Encrypt)); assert!(k1.can(super::Encrypt));
assert!(!k1.can(Decrypt)); assert!(!k1.can(super::Decrypt));
assert!(k1.can(Verify)); assert!(k1.can(super::Verify));
assert!(!k1.can(Sign)); assert!(!k1.can(super::Sign));
} }
#[test] #[test]
fn test_gen_priv() { fn test_gen_priv() {
let mut k0 = PKey::new(); let mut k0 = super::PKey::new();
let mut k1 = PKey::new(); let mut k1 = super::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_eq!(k0.save_priv(), k1.save_priv());
assert!(k0.size() == k1.size()); assert_eq!(k0.size(), k1.size());
assert!(k0.can(Encrypt)); assert!(k0.can(super::Encrypt));
assert!(k0.can(Decrypt)); assert!(k0.can(super::Decrypt));
assert!(k0.can(Verify)); assert!(k0.can(super::Verify));
assert!(k0.can(Sign)); assert!(k0.can(super::Sign));
assert!(k1.can(Encrypt)); assert!(k1.can(super::Encrypt));
assert!(k1.can(Decrypt)); assert!(k1.can(super::Decrypt));
assert!(k1.can(Verify)); assert!(k1.can(super::Verify));
assert!(k1.can(Sign)); assert!(k1.can(super::Sign));
} }
#[test] #[test]
fn test_encrypt() { fn test_encrypt() {
let mut k0 = PKey::new(); let mut k0 = super::PKey::new();
let mut k1 = PKey::new(); let mut k1 = super::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());
@ -413,20 +388,20 @@ mod tests {
#[test] #[test]
fn test_encrypt_pkcs() { fn test_encrypt_pkcs() {
let mut k0 = PKey::new(); let mut k0 = super::PKey::new();
let mut k1 = PKey::new(); let mut k1 = super::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());
let emsg = k1.encrypt_with_padding(msg, PKCS1v15); let emsg = k1.encrypt_with_padding(msg, super::PKCS1v15);
let dmsg = k0.decrypt_with_padding(emsg, PKCS1v15); let dmsg = k0.decrypt_with_padding(emsg, super::PKCS1v15);
assert!(msg == dmsg); assert!(msg == dmsg);
} }
#[test] #[test]
fn test_sign() { fn test_sign() {
let mut k0 = PKey::new(); let mut k0 = super::PKey::new();
let mut k1 = PKey::new(); let mut k1 = super::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());
@ -437,8 +412,8 @@ mod tests {
#[test] #[test]
fn test_sign_hashes() { fn test_sign_hashes() {
let mut k0 = PKey::new(); let mut k0 = super::PKey::new();
let mut k1 = PKey::new(); let mut k1 = super::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());

View File

@ -1,31 +1,27 @@
use std::libc::c_int; use std::libc::c_int;
use std::vec; use std::vec;
mod libcrypto { #[link(name = "crypto")]
use std::libc::c_int; extern {
fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int;
#[link(name = "crypto")]
extern {
pub 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); unsafe {
let mut out = vec::with_capacity(len);
out.as_mut_buf(|out_buf, len| { let r = RAND_bytes(out.as_mut_ptr(), len as c_int);
let r = unsafe { libcrypto::RAND_bytes(out_buf, len as c_int) };
if r != 1 as c_int { fail!() } if r != 1 as c_int { fail!() }
});
unsafe { out.set_len(len); } out.set_len(len);
out out
}
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::rand_bytes;
#[test] #[test]
fn test_rand_bytes() { fn test_rand_bytes() {

View File

@ -1,4 +1,4 @@
use std::libc::c_int; use std::libc::{c_int, c_uint};
use std::libc; use std::libc;
use std::vec; use std::vec;
@ -8,34 +8,29 @@ pub type EVP_CIPHER_CTX = *libc::c_void;
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
pub type EVP_CIPHER = *libc::c_void; pub type EVP_CIPHER = *libc::c_void;
mod libcrypto { #[link(name = "crypto")]
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_CIPHER_CTX_free(ctx: EVP_CIPHER_CTX);
extern { fn EVP_aes_128_ecb() -> EVP_CIPHER;
#[link_args = "-lcrypto"] fn EVP_aes_128_cbc() -> EVP_CIPHER;
pub fn EVP_CIPHER_CTX_new() -> EVP_CIPHER_CTX; // fn EVP_aes_128_ctr() -> EVP_CIPHER;
pub fn EVP_CIPHER_CTX_set_padding(ctx: EVP_CIPHER_CTX, padding: c_int); // fn EVP_aes_128_gcm() -> EVP_CIPHER;
pub fn EVP_CIPHER_CTX_free(ctx: EVP_CIPHER_CTX);
pub fn EVP_aes_128_ecb() -> EVP_CIPHER; fn EVP_aes_256_ecb() -> EVP_CIPHER;
pub fn EVP_aes_128_cbc() -> EVP_CIPHER; fn EVP_aes_256_cbc() -> EVP_CIPHER;
// pub fn EVP_aes_128_ctr() -> EVP_CIPHER; // fn EVP_aes_256_ctr() -> EVP_CIPHER;
// pub fn EVP_aes_128_gcm() -> EVP_CIPHER; // fn EVP_aes_256_gcm() -> EVP_CIPHER;
pub fn EVP_aes_256_ecb() -> EVP_CIPHER; fn EVP_rc4() -> EVP_CIPHER;
pub fn EVP_aes_256_cbc() -> EVP_CIPHER;
// pub fn EVP_aes_256_ctr() -> EVP_CIPHER;
// pub fn EVP_aes_256_gcm() -> EVP_CIPHER;
pub fn EVP_rc4() -> EVP_CIPHER; fn EVP_CipherInit(ctx: EVP_CIPHER_CTX, evp: EVP_CIPHER,
key: *u8, iv: *u8, mode: c_int);
pub fn EVP_CipherInit(ctx: EVP_CIPHER_CTX, evp: EVP_CIPHER, fn EVP_CipherUpdate(ctx: EVP_CIPHER_CTX, outbuf: *mut u8,
key: *u8, iv: *u8, mode: c_int); outlen: &mut c_uint, inbuf: *u8, inlen: c_int);
pub fn EVP_CipherUpdate(ctx: EVP_CIPHER_CTX, outbuf: *mut u8, fn EVP_CipherFinal(ctx: EVP_CIPHER_CTX, res: *mut u8, len: &mut c_int);
outlen: &mut c_uint, inbuf: *u8, inlen: c_int);
pub fn EVP_CipherFinal(ctx: EVP_CIPHER_CTX, res: *mut u8, len: &mut c_int);
}
} }
pub enum Mode { pub enum Mode {
@ -61,17 +56,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 => (libcrypto::EVP_aes_128_ecb(), 16u, 16u), AES_128_ECB => (EVP_aes_128_ecb(), 16u, 16u),
AES_128_CBC => (libcrypto::EVP_aes_128_cbc(), 16u, 16u), AES_128_CBC => (EVP_aes_128_cbc(), 16u, 16u),
// AES_128_CTR => (libcrypto::EVP_aes_128_ctr(), 16u, 0u), // AES_128_CTR => (EVP_aes_128_ctr(), 16u, 0u),
//AES_128_GCM => (libcrypto::EVP_aes_128_gcm(), 16u, 16u), //AES_128_GCM => (EVP_aes_128_gcm(), 16u, 16u),
AES_256_ECB => (libcrypto::EVP_aes_256_ecb(), 32u, 16u), AES_256_ECB => (EVP_aes_256_ecb(), 32u, 16u),
AES_256_CBC => (libcrypto::EVP_aes_256_cbc(), 32u, 16u), AES_256_CBC => (EVP_aes_256_cbc(), 32u, 16u),
// AES_256_CTR => (libcrypto::EVP_aes_256_ctr(), 32u, 0u), // AES_256_CTR => (EVP_aes_256_ctr(), 32u, 0u),
//AES_256_GCM => (libcrypto::EVP_aes_256_gcm(), 32u, 16u), //AES_256_GCM => (EVP_aes_256_gcm(), 32u, 16u),
RC4_128 => (libcrypto::EVP_rc4(), 16u, 0u), RC4_128 => (EVP_rc4(), 16u, 0u),
} }
} }
} }
@ -86,7 +81,7 @@ pub struct Crypter {
impl Crypter { impl Crypter {
pub fn new(t: Type) -> Crypter { pub fn new(t: Type) -> Crypter {
let ctx = unsafe { libcrypto::EVP_CIPHER_CTX_new() }; let ctx = unsafe { 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 }
} }
@ -99,7 +94,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;
libcrypto::EVP_CIPHER_CTX_set_padding(self.ctx, v); EVP_CIPHER_CTX_set_padding(self.ctx, v);
} }
} }
} }
@ -115,17 +110,13 @@ impl Crypter {
}; };
assert_eq!(key.len(), self.keylen); assert_eq!(key.len(), self.keylen);
key.as_imm_buf(|pkey, _len| { EVP_CipherInit(
iv.as_imm_buf(|piv, _len| { self.ctx,
libcrypto::EVP_CipherInit( self.evp,
self.ctx, key.as_ptr(),
self.evp, iv.as_ptr(),
pkey, mode
piv, )
mode
)
});
});
} }
} }
@ -135,26 +126,19 @@ impl Crypter {
*/ */
pub fn update(&self, data: &[u8]) -> ~[u8] { pub fn update(&self, data: &[u8]) -> ~[u8] {
unsafe { unsafe {
data.as_imm_buf(|pdata, len| { let mut res = vec::from_elem(data.len() + self.blocksize, 0u8);
let mut res = vec::from_elem(len + self.blocksize, 0u8); let mut reslen = (data.len() + self.blocksize) as u32;
let reslen = res.as_mut_buf(|pres, _len| { EVP_CipherUpdate(
let mut reslen = (len + self.blocksize) as u32; self.ctx,
res.as_mut_ptr(),
&mut reslen,
data.as_ptr(),
data.len() as c_int
);
libcrypto::EVP_CipherUpdate( res.truncate(reslen as uint);
self.ctx, res
pres,
&mut reslen,
pdata,
len as c_int
);
reslen
});
res.truncate(reslen as uint);
res
})
} }
} }
@ -164,12 +148,11 @@ impl Crypter {
pub fn final(&self) -> ~[u8] { pub fn final(&self) -> ~[u8] {
unsafe { unsafe {
let mut res = vec::from_elem(self.blocksize, 0u8); let mut res = vec::from_elem(self.blocksize, 0u8);
let mut reslen = self.blocksize as c_int;
let reslen = res.as_mut_buf(|pres, _len| { EVP_CipherFinal(self.ctx,
let mut reslen = self.blocksize as c_int; res.as_mut_ptr(),
libcrypto::EVP_CipherFinal(self.ctx, pres, &mut reslen); &mut reslen);
reslen
});
res.truncate(reslen as uint); res.truncate(reslen as uint);
res res
@ -180,7 +163,7 @@ impl Crypter {
impl Drop for Crypter { impl Drop for Crypter {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
libcrypto::EVP_CIPHER_CTX_free(self.ctx); EVP_CIPHER_CTX_free(self.ctx);
} }
} }
} }
@ -211,8 +194,6 @@ pub fn decrypt(t: Type, key: &[u8], iv: ~[u8], data: &[u8]) -> ~[u8] {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use hex::FromHex; use hex::FromHex;
// Test vectors from FIPS-197: // Test vectors from FIPS-197:
@ -230,22 +211,22 @@ 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::new(AES_256_ECB); let c = super::Crypter::new(super::AES_256_ECB);
c.init(Encrypt, k0, []); c.init(super::Encrypt, k0, []);
c.pad(false); c.pad(false);
let r0 = c.update(p0) + c.final(); let r0 = c.update(p0) + c.final();
assert!(r0 == c0); assert!(r0 == c0);
c.init(Decrypt, k0, []); c.init(super::Decrypt, k0, []);
c.pad(false); c.pad(false);
let p1 = c.update(r0) + c.final(); let p1 = c.update(r0) + c.final();
assert!(p1 == p0); assert!(p1 == p0);
} }
fn cipher_test(ciphertype: Type, pt: ~str, ct: ~str, key: ~str, iv: ~str) { fn cipher_test(ciphertype: super::Type, pt: ~str, ct: ~str, key: ~str, iv: ~str) {
use hex::ToHex; use hex::ToHex;
let cipher = Crypter::new(ciphertype); let cipher = super::Crypter::new(ciphertype);
cipher.init(Encrypt, key.from_hex(), iv.from_hex()); cipher.init(super::Encrypt, key.from_hex(), iv.from_hex());
let expected = ct.from_hex(); let expected = ct.from_hex();
let computed = cipher.update(pt.from_hex()) + cipher.final(); let computed = cipher.update(pt.from_hex()) + cipher.final();
@ -269,7 +250,7 @@ mod tests {
let key = ~"97CD440324DA5FD1F7955C1C13B6B466"; let key = ~"97CD440324DA5FD1F7955C1C13B6B466";
let iv = ~""; let iv = ~"";
cipher_test(RC4_128, pt, ct, key, iv); cipher_test(super::RC4_128, pt, ct, key, iv);
} }
/*#[test] /*#[test]
@ -280,7 +261,7 @@ mod tests {
let key = ~"2B7E151628AED2A6ABF7158809CF4F3C"; let key = ~"2B7E151628AED2A6ABF7158809CF4F3C";
let iv = ~"F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; let iv = ~"F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
cipher_test(AES_128_CTR, pt, ct, key, iv); cipher_test(super::AES_128_CTR, pt, ct, key, iv);
}*/ }*/
/*#[test] /*#[test]
@ -291,6 +272,6 @@ mod tests {
let key = ~"feffe9928665731c6d6a8f9467308308"; let key = ~"feffe9928665731c6d6a8f9467308308";
let iv = ~"cafebabefacedbaddecaf888"; let iv = ~"cafebabefacedbaddecaf888";
cipher_test(AES_128_GCM, pt, ct, key, iv); cipher_test(super::AES_128_GCM, pt, ct, key, iv);
}*/ }*/
} }