Loading hash.rs +44 −31 Original line number Diff line number Diff line use libc::c_uint; use core::libc::c_uint; pub enum HashType { MD5, Loading @@ -10,10 +10,10 @@ pub enum HashType { } #[allow(non_camel_case_types)] type EVP_MD_CTX = *libc::c_void; pub type EVP_MD_CTX = *libc::c_void; #[allow(non_camel_case_types)] type EVP_MD = *libc::c_void; pub type EVP_MD = *libc::c_void; #[link_name = "crypto"] #[abi = "cdecl"] Loading @@ -32,7 +32,8 @@ extern mod libcrypto { fn EVP_DigestFinal(ctx: EVP_MD_CTX, res: *mut u8, n: *u32); } fn evpmd(t: HashType) -> (EVP_MD, uint) { pub fn evpmd(t: HashType) -> (EVP_MD, uint) { unsafe { match t { MD5 => (libcrypto::EVP_md5(), 16u), SHA1 => (libcrypto::EVP_sha1(), 20u), Loading @@ -42,6 +43,7 @@ fn evpmd(t: HashType) -> (EVP_MD, uint) { SHA512 => (libcrypto::EVP_sha512(), 64u), } } } pub struct Hasher { priv evp: EVP_MD, Loading @@ -50,31 +52,38 @@ pub struct Hasher { } pub fn Hasher(ht: HashType) -> Hasher { unsafe { let ctx = libcrypto::EVP_MD_CTX_create(); let (evp, mdlen) = evpmd(ht); let h = Hasher { evp: evp, ctx: ctx, len: mdlen }; h.init(); h } } pub impl Hasher { /// Initializes this hasher fn init() unsafe { fn init(&self) { unsafe { libcrypto::EVP_DigestInit(self.ctx, self.evp); } } /// Update this hasher with more input bytes fn update(data: &[u8]) unsafe { fn update(&self, data: &[u8]) { unsafe { do vec::as_imm_buf(data) |pdata, len| { libcrypto::EVP_DigestUpdate(self.ctx, pdata, len as c_uint) } } } /** * Return the digest of all bytes added to this hasher since its last * initialization */ fn final() -> ~[u8] unsafe { fn final(&self) -> ~[u8] { unsafe { let mut res = vec::from_elem(self.len, 0u8); do vec::as_mut_buf(res) |pres, _len| { libcrypto::EVP_DigestFinal(self.ctx, pres, ptr::null()); Loading @@ -82,19 +91,23 @@ pub impl Hasher { res } } } /** * Hashes the supplied input data using hash t, returning the resulting hash * value */ pub fn hash(t: HashType, data: &[u8]) -> ~[u8] unsafe { pub fn hash(t: HashType, data: &[u8]) -> ~[u8] { unsafe { let h = Hasher(t); h.update(data); h.final() } } #[cfg(test)] mod tests { use super::*; use hex::FromHex; use hex::ToHex; Loading @@ -117,7 +130,7 @@ mod tests { io::println(fmt!("Test failed - %s != %s", calced, hashtest.expected_output)); } assert calced == hashtest.expected_output; assert!(calced == hashtest.expected_output); } // Test vectors from http://www.nsrl.nist.gov/testdata/ Loading hex.rs +13 −12 Original line number Diff line number Diff line Loading @@ -17,13 +17,13 @@ extern mod std; pub trait ToHex { pure fn to_hex() -> ~str; fn to_hex(&self) -> ~str; } impl &[u8]: ToHex { pure fn to_hex() -> ~str { impl<'self> ToHex for &'self [u8] { fn to_hex(&self) -> ~str { let chars = str::chars(~"0123456789ABCDEF"); let chars = str::to_chars(~"0123456789ABCDEF"); let mut s = ~""; Loading @@ -45,20 +45,20 @@ impl &[u8]: ToHex { } pub trait FromHex { pure fn from_hex() -> ~[u8]; fn from_hex(&self) -> ~[u8]; } impl &str: FromHex { pure fn from_hex() -> ~[u8] { impl<'self> FromHex for &'self str { fn from_hex(&self) -> ~[u8] { let mut vec = vec::with_capacity(self.len() / 2); for str::each_chari(self) |i,c| { for str::each_chari(*self) |i,c| { let nibble = if c >= '0' && c <= '9' { (c as u8) - 0x30 } else if c >= 'a' && c <= 'f' { (c as u8) - (0x61 - 10) } else if c >= 'A' && c <= 'F' { (c as u8) - (0x41 - 10) } else { fail ~"bad hex character"; }; else { fail!(~"bad hex character"); }; if i % 2 == 0 { unsafe { Loading @@ -76,15 +76,16 @@ impl &str: FromHex { #[cfg(test)] mod tests { use super::*; #[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"); } Loading hmac.rs +23 −19 Original line number Diff line number Diff line Loading @@ -17,13 +17,13 @@ use hash::*; #[allow(non_camel_case_types)] struct HMAC_CTX { mut md: EVP_MD, mut md_ctx: EVP_MD_CTX, mut i_ctx: EVP_MD_CTX, mut o_ctx: EVP_MD_CTX, mut key_length: libc::c_uint, mut key: [libc::c_uchar * 128] pub struct HMAC_CTX { md: EVP_MD, md_ctx: EVP_MD_CTX, i_ctx: EVP_MD_CTX, o_ctx: EVP_MD_CTX, key_length: libc::c_uint, key: [libc::c_uchar, ..128] } #[link_name = "crypto"] Loading @@ -38,7 +38,7 @@ extern mod libcrypto { } pub struct HMAC { priv mut ctx: HMAC_CTX, priv ctx: HMAC_CTX, priv len: uint, } Loading Loading @@ -66,25 +66,29 @@ pub fn HMAC(ht: HashType, key: ~[u8]) -> HMAC { } pub impl HMAC { fn update(data: &[u8]) unsafe { fn update(&mut self, data: &[u8]) { unsafe { do vec::as_imm_buf(data) |pdata, len| { libcrypto::HMAC_Update(&mut self.ctx, pdata, len as libc::c_uint) } } } fn final() -> ~[u8] unsafe { fn final(&mut self) -> ~[u8] { unsafe { let mut res = vec::from_elem(self.len, 0u8); let mut outlen: libc::c_uint = 0; do vec::as_mut_buf(res) |pres, _len| { libcrypto::HMAC_Final(&mut self.ctx, pres, &mut outlen); assert self.len == outlen as uint assert!(self.len == outlen as uint) } res } } } fn main() { let h = HMAC(SHA512, ~[00u8]); let mut h = HMAC(SHA512, ~[00u8]); h.update(~[00u8]); Loading pkcs5.rs +25 −21 Original line number Diff line number Diff line use libc::{c_char, c_uchar, c_int}; use core::libc::c_int; #[link_name = "crypto"] #[abi = "cdecl"] Loading @@ -14,21 +14,23 @@ 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, keylen: uint) -> ~[u8] { assert iter >= 1u; assert keylen >= 1u; assert!(iter >= 1u); assert!(keylen >= 1u); do str::as_buf(pass) |pass_buf, pass_len| { do vec::as_imm_buf(salt) |salt_buf, salt_len| { let mut out = vec::with_capacity(keylen); do vec::as_mut_buf(out) |out_buf, _out_len| { unsafe { let r = libcrypto::PKCS5_PBKDF2_HMAC_SHA1( pass_buf, pass_len as c_int, salt_buf, salt_len as c_int, iter as c_int, keylen as c_int, out_buf); if r != 1 as c_int { fail; } if r != 1 as c_int { fail!(); } } } unsafe { vec::raw::set_len(&mut out, keylen); } Loading @@ -40,11 +42,13 @@ pub fn pbkdf2_hmac_sha1(pass: &str, salt: &[u8], iter: uint, #[cfg(test)] mod tests { use super::*; // Test vectors from // http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 #[test] fn test_pbkdf2_hmac_sha1() { assert pbkdf2_hmac_sha1( assert!(pbkdf2_hmac_sha1( "password", str::to_bytes("salt"), 1u, Loading @@ -53,9 +57,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "password", str::to_bytes("salt"), 2u, Loading @@ -64,9 +68,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "password", str::to_bytes("salt"), 4096u, Loading @@ -75,9 +79,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "password", str::to_bytes("salt"), 16777216u, Loading @@ -86,9 +90,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "passwordPASSWORDpassword", str::to_bytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"), 4096u, Loading @@ -98,9 +102,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "pass\x00word", str::to_bytes("sa\x00lt"), 4096u, Loading @@ -109,6 +113,6 @@ mod tests { 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 ]; ]); } } pkey.rs +215 −179 Original line number Diff line number Diff line use libc::{c_int, c_uint}; use core::libc::{c_int, c_uint}; use hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512}; #[allow(non_camel_case_types)] Loading Loading @@ -74,25 +74,33 @@ fn openssl_hash_nid(hash: HashType) -> c_int { } } fn rsa_to_any(rsa: *RSA) -> *ANYKEY unsafe { fn rsa_to_any(rsa: *RSA) -> *ANYKEY { unsafe { cast::reinterpret_cast(&rsa) } } fn any_to_rsa(anykey: *ANYKEY) -> *RSA unsafe { fn any_to_rsa(anykey: *ANYKEY) -> *RSA { unsafe { cast::reinterpret_cast(&anykey) } } pub struct PKey { priv mut evp: *EVP_PKEY, priv mut parts: Parts, priv evp: *EVP_PKEY, priv parts: Parts, } pub fn PKey() -> PKey { unsafe { PKey { evp: libcrypto::EVP_PKEY_new(), parts: Neither } } } ///Represents a public key, optionally with a private key attached. priv impl PKey { fn _tostr(f: fn@(*EVP_PKEY, &*mut u8) -> c_int) -> ~[u8] unsafe { priv fn _tostr(&self, f: @fn(*EVP_PKEY, &*mut u8) -> c_int) -> ~[u8] { unsafe { let buf = ptr::mut_null(); let len = f(self.evp, &buf); if len < 0 as c_int { return ~[]; } Loading @@ -102,13 +110,16 @@ priv impl PKey { f(self.evp, &ps) }; vec::slice(s, 0u, r as uint) vec::slice(s, 0u, r as uint).to_owned() } } fn _fromstr( priv fn _fromstr( &mut self, s: &[u8], f: fn@(c_int, &*EVP_PKEY, &*u8, c_uint) -> *EVP_PKEY ) unsafe { f: @fn(c_int, &*EVP_PKEY, &*u8, c_uint) -> *EVP_PKEY ) { unsafe { do vec::as_imm_buf(s) |ps, len| { let evp = ptr::null(); f(6 as c_int, &evp, &ps, len as c_uint); Loading @@ -116,10 +127,11 @@ priv impl PKey { } } } } ///Represents a public key, optionally with a private key attached. pub impl PKey { fn gen(keysz: uint) unsafe { fn gen(&mut self, keysz: uint) { unsafe { let rsa = libcrypto::RSA_generate_key( keysz as c_uint, 65537u as c_uint, Loading @@ -132,49 +144,60 @@ pub impl PKey { libcrypto::EVP_PKEY_assign(self.evp, 6 as c_int, rsa_); self.parts = Both; } } /** * Returns a serialized form of the public key, suitable for load_pub(). */ fn save_pub() -> ~[u8] { fn save_pub(&self) -> ~[u8] { unsafe { self._tostr(libcrypto::i2d_PublicKey) } } /** * Loads a serialized form of the public key, as produced by save_pub(). */ fn load_pub(s: &[u8]) { fn load_pub(&mut self, s: &[u8]) { unsafe { self._fromstr(s, libcrypto::d2i_PublicKey); self.parts = Public; } } /** * Returns a serialized form of the public and private keys, suitable for * load_priv(). */ fn save_priv() -> ~[u8] { fn save_priv(&self, ) -> ~[u8] { unsafe { self._tostr(libcrypto::i2d_PrivateKey) } } /** * Loads a serialized form of the public and private keys, as produced by * save_priv(). */ fn load_priv(s: &[u8]) { fn load_priv(&mut self, s: &[u8]) { unsafe { self._fromstr(s, libcrypto::d2i_PrivateKey); self.parts = Both; } } /** * Returns the size of the public key modulus. */ fn size() -> uint { fn size(&self) -> uint { unsafe { libcrypto::RSA_size(libcrypto::EVP_PKEY_get1_RSA(self.evp)) as uint } } /** * Returns whether this pkey object can perform the specified role. */ fn can(r: Role) -> bool { fn can(&self, r: Role) -> bool { match r { Encrypt => match self.parts { Loading Loading @@ -203,19 +226,22 @@ pub impl PKey { * Returns the maximum amount of data that can be encrypted by an encrypt() * call. */ fn max_data() -> uint unsafe { fn max_data(&self) -> uint { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let len = libcrypto::RSA_size(rsa); // 41 comes from RSA_public_encrypt(3) for OAEP len as uint - 41u } } fn encrypt_with_padding(s: &[u8], padding: EncryptionPadding) -> ~[u8] unsafe { fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> ~[u8] { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let len = libcrypto::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); Loading @@ -232,17 +258,19 @@ pub impl PKey { if rv < 0 as c_int { ~[] } else { vec::slice(r, 0u, rv as uint) vec::const_slice(r, 0u, rv as uint).to_owned() } } } } } fn decrypt_with_padding(s: &[u8], padding: EncryptionPadding) -> ~[u8] unsafe { fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> ~[u8] { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let len = libcrypto::RSA_size(rsa); assert s.len() as c_uint == libcrypto::RSA_size(rsa); assert!(s.len() as c_uint == libcrypto::RSA_size(rsa)); let mut r = vec::from_elem(len as uint + 1u, 0u8); Loading @@ -259,7 +287,8 @@ pub impl PKey { if rv < 0 as c_int { ~[] } else { vec::slice(r, 0u, rv as uint) vec::const_slice(r, 0u, rv as uint).to_owned() } } } } Loading @@ -269,26 +298,27 @@ pub impl PKey { * Encrypts data using OAEP padding, returning the encrypted data. The * supplied data must not be larger than max_data(). */ fn encrypt(s: &[u8]) -> ~[u8] unsafe { self.encrypt_with_padding(s, OAEP) } fn encrypt(&self, s: &[u8]) -> ~[u8] { unsafe { self.encrypt_with_padding(s, OAEP) } } /** * Decrypts data, expecting OAEP padding, returning the decrypted data. */ fn decrypt(s: &[u8]) -> ~[u8] unsafe { self.decrypt_with_padding(s, OAEP) } fn decrypt(&self, s: &[u8]) -> ~[u8] { unsafe { self.decrypt_with_padding(s, OAEP) } } /** * Signs data, using OpenSSL's default scheme and sha256. Unlike encrypt(), * can process an arbitrary amount of data; returns the signature. */ fn sign(s: &[u8]) -> ~[u8] unsafe { self.sign_with_hash(s, SHA256) } fn sign(&self, s: &[u8]) -> ~[u8] { unsafe { self.sign_with_hash(s, SHA256) } } /** * Verifies a signature s (using OpenSSL's default scheme and sha256) on a * message m. Returns true if the signature is valid, and false otherwise. */ fn verify(m: &[u8], s: &[u8]) -> bool unsafe { self.verify_with_hash(m, s, SHA256) } fn verify(&self, m: &[u8], s: &[u8]) -> bool { unsafe { self.verify_with_hash(m, s, SHA256) } } fn sign_with_hash(s: &[u8], hash: HashType) -> ~[u8] unsafe { fn sign_with_hash(&self, s: &[u8], hash: HashType) -> ~[u8] { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let len = libcrypto::RSA_size(rsa); let mut r = vec::from_elem(len as uint + 1u, 0u8); Loading @@ -308,13 +338,15 @@ pub impl PKey { if rv < 0 as c_int { ~[] } else { vec::slice(r, 0u, *plen as uint) vec::const_slice(r, 0u, *plen as uint).to_owned() } } } } } fn verify_with_hash(m: &[u8], s: &[u8], hash: HashType) -> bool unsafe { fn verify_with_hash(&self, m: &[u8], s: &[u8], hash: HashType) -> bool { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); do vec::as_imm_buf(m) |pm, m_len| { Loading @@ -333,93 +365,97 @@ pub impl PKey { } } } } #[cfg(test)] mod tests { use super::*; use hash::{MD5, SHA1}; #[test] fn test_gen_pub() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); k0.gen(512u); k1.load_pub(k0.save_pub()); assert(k0.save_pub() == k1.save_pub()); assert(k0.size() == k1.size()); assert(k0.can(Encrypt)); assert(k0.can(Decrypt)); assert(k0.can(Verify)); assert(k0.can(Sign)); assert(k1.can(Encrypt)); assert(!k1.can(Decrypt)); assert(k1.can(Verify)); assert(!k1.can(Sign)); assert!(k0.save_pub() == k1.save_pub()); assert!(k0.size() == k1.size()); assert!(k0.can(Encrypt)); assert!(k0.can(Decrypt)); assert!(k0.can(Verify)); assert!(k0.can(Sign)); assert!(k1.can(Encrypt)); assert!(!k1.can(Decrypt)); assert!(k1.can(Verify)); assert!(!k1.can(Sign)); } #[test] fn test_gen_priv() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); k0.gen(512u); k1.load_priv(k0.save_priv()); assert(k0.save_priv() == k1.save_priv()); assert(k0.size() == k1.size()); assert(k0.can(Encrypt)); assert(k0.can(Decrypt)); assert(k0.can(Verify)); assert(k0.can(Sign)); assert(k1.can(Encrypt)); assert(k1.can(Decrypt)); assert(k1.can(Verify)); assert(k1.can(Sign)); assert!(k0.save_priv() == k1.save_priv()); assert!(k0.size() == k1.size()); assert!(k0.can(Encrypt)); assert!(k0.can(Decrypt)); assert!(k0.can(Verify)); assert!(k0.can(Sign)); assert!(k1.can(Encrypt)); assert!(k1.can(Decrypt)); assert!(k1.can(Verify)); assert!(k1.can(Sign)); } #[test] fn test_encrypt() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; k0.gen(512u); k1.load_pub(k0.save_pub()); let emsg = k1.encrypt(msg); let dmsg = k0.decrypt(emsg); assert(msg == dmsg); assert!(msg == dmsg); } #[test] fn test_encrypt_pkcs() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; k0.gen(512u); k1.load_pub(k0.save_pub()); let emsg = k1.encrypt_with_padding(msg, PKCS1v15); let dmsg = k0.decrypt_with_padding(emsg, PKCS1v15); assert(msg == dmsg); assert!(msg == dmsg); } #[test] fn test_sign() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; k0.gen(512u); k1.load_pub(k0.save_pub()); let sig = k0.sign(msg); let rv = k1.verify(msg, sig); assert(rv == true); assert!(rv == true); } #[test] fn test_sign_hashes() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; k0.gen(512u); k1.load_pub(k0.save_pub()); let sig = k0.sign_with_hash(msg, MD5); assert k1.verify_with_hash(msg, sig, MD5); assert !k1.verify_with_hash(msg, sig, SHA1); assert!(k1.verify_with_hash(msg, sig, MD5)); assert!(!k1.verify_with_hash(msg, sig, SHA1)); } } Loading
hash.rs +44 −31 Original line number Diff line number Diff line use libc::c_uint; use core::libc::c_uint; pub enum HashType { MD5, Loading @@ -10,10 +10,10 @@ pub enum HashType { } #[allow(non_camel_case_types)] type EVP_MD_CTX = *libc::c_void; pub type EVP_MD_CTX = *libc::c_void; #[allow(non_camel_case_types)] type EVP_MD = *libc::c_void; pub type EVP_MD = *libc::c_void; #[link_name = "crypto"] #[abi = "cdecl"] Loading @@ -32,7 +32,8 @@ extern mod libcrypto { fn EVP_DigestFinal(ctx: EVP_MD_CTX, res: *mut u8, n: *u32); } fn evpmd(t: HashType) -> (EVP_MD, uint) { pub fn evpmd(t: HashType) -> (EVP_MD, uint) { unsafe { match t { MD5 => (libcrypto::EVP_md5(), 16u), SHA1 => (libcrypto::EVP_sha1(), 20u), Loading @@ -42,6 +43,7 @@ fn evpmd(t: HashType) -> (EVP_MD, uint) { SHA512 => (libcrypto::EVP_sha512(), 64u), } } } pub struct Hasher { priv evp: EVP_MD, Loading @@ -50,31 +52,38 @@ pub struct Hasher { } pub fn Hasher(ht: HashType) -> Hasher { unsafe { let ctx = libcrypto::EVP_MD_CTX_create(); let (evp, mdlen) = evpmd(ht); let h = Hasher { evp: evp, ctx: ctx, len: mdlen }; h.init(); h } } pub impl Hasher { /// Initializes this hasher fn init() unsafe { fn init(&self) { unsafe { libcrypto::EVP_DigestInit(self.ctx, self.evp); } } /// Update this hasher with more input bytes fn update(data: &[u8]) unsafe { fn update(&self, data: &[u8]) { unsafe { do vec::as_imm_buf(data) |pdata, len| { libcrypto::EVP_DigestUpdate(self.ctx, pdata, len as c_uint) } } } /** * Return the digest of all bytes added to this hasher since its last * initialization */ fn final() -> ~[u8] unsafe { fn final(&self) -> ~[u8] { unsafe { let mut res = vec::from_elem(self.len, 0u8); do vec::as_mut_buf(res) |pres, _len| { libcrypto::EVP_DigestFinal(self.ctx, pres, ptr::null()); Loading @@ -82,19 +91,23 @@ pub impl Hasher { res } } } /** * Hashes the supplied input data using hash t, returning the resulting hash * value */ pub fn hash(t: HashType, data: &[u8]) -> ~[u8] unsafe { pub fn hash(t: HashType, data: &[u8]) -> ~[u8] { unsafe { let h = Hasher(t); h.update(data); h.final() } } #[cfg(test)] mod tests { use super::*; use hex::FromHex; use hex::ToHex; Loading @@ -117,7 +130,7 @@ mod tests { io::println(fmt!("Test failed - %s != %s", calced, hashtest.expected_output)); } assert calced == hashtest.expected_output; assert!(calced == hashtest.expected_output); } // Test vectors from http://www.nsrl.nist.gov/testdata/ Loading
hex.rs +13 −12 Original line number Diff line number Diff line Loading @@ -17,13 +17,13 @@ extern mod std; pub trait ToHex { pure fn to_hex() -> ~str; fn to_hex(&self) -> ~str; } impl &[u8]: ToHex { pure fn to_hex() -> ~str { impl<'self> ToHex for &'self [u8] { fn to_hex(&self) -> ~str { let chars = str::chars(~"0123456789ABCDEF"); let chars = str::to_chars(~"0123456789ABCDEF"); let mut s = ~""; Loading @@ -45,20 +45,20 @@ impl &[u8]: ToHex { } pub trait FromHex { pure fn from_hex() -> ~[u8]; fn from_hex(&self) -> ~[u8]; } impl &str: FromHex { pure fn from_hex() -> ~[u8] { impl<'self> FromHex for &'self str { fn from_hex(&self) -> ~[u8] { let mut vec = vec::with_capacity(self.len() / 2); for str::each_chari(self) |i,c| { for str::each_chari(*self) |i,c| { let nibble = if c >= '0' && c <= '9' { (c as u8) - 0x30 } else if c >= 'a' && c <= 'f' { (c as u8) - (0x61 - 10) } else if c >= 'A' && c <= 'F' { (c as u8) - (0x41 - 10) } else { fail ~"bad hex character"; }; else { fail!(~"bad hex character"); }; if i % 2 == 0 { unsafe { Loading @@ -76,15 +76,16 @@ impl &str: FromHex { #[cfg(test)] mod tests { use super::*; #[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"); } Loading
hmac.rs +23 −19 Original line number Diff line number Diff line Loading @@ -17,13 +17,13 @@ use hash::*; #[allow(non_camel_case_types)] struct HMAC_CTX { mut md: EVP_MD, mut md_ctx: EVP_MD_CTX, mut i_ctx: EVP_MD_CTX, mut o_ctx: EVP_MD_CTX, mut key_length: libc::c_uint, mut key: [libc::c_uchar * 128] pub struct HMAC_CTX { md: EVP_MD, md_ctx: EVP_MD_CTX, i_ctx: EVP_MD_CTX, o_ctx: EVP_MD_CTX, key_length: libc::c_uint, key: [libc::c_uchar, ..128] } #[link_name = "crypto"] Loading @@ -38,7 +38,7 @@ extern mod libcrypto { } pub struct HMAC { priv mut ctx: HMAC_CTX, priv ctx: HMAC_CTX, priv len: uint, } Loading Loading @@ -66,25 +66,29 @@ pub fn HMAC(ht: HashType, key: ~[u8]) -> HMAC { } pub impl HMAC { fn update(data: &[u8]) unsafe { fn update(&mut self, data: &[u8]) { unsafe { do vec::as_imm_buf(data) |pdata, len| { libcrypto::HMAC_Update(&mut self.ctx, pdata, len as libc::c_uint) } } } fn final() -> ~[u8] unsafe { fn final(&mut self) -> ~[u8] { unsafe { let mut res = vec::from_elem(self.len, 0u8); let mut outlen: libc::c_uint = 0; do vec::as_mut_buf(res) |pres, _len| { libcrypto::HMAC_Final(&mut self.ctx, pres, &mut outlen); assert self.len == outlen as uint assert!(self.len == outlen as uint) } res } } } fn main() { let h = HMAC(SHA512, ~[00u8]); let mut h = HMAC(SHA512, ~[00u8]); h.update(~[00u8]); Loading
pkcs5.rs +25 −21 Original line number Diff line number Diff line use libc::{c_char, c_uchar, c_int}; use core::libc::c_int; #[link_name = "crypto"] #[abi = "cdecl"] Loading @@ -14,21 +14,23 @@ 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, keylen: uint) -> ~[u8] { assert iter >= 1u; assert keylen >= 1u; assert!(iter >= 1u); assert!(keylen >= 1u); do str::as_buf(pass) |pass_buf, pass_len| { do vec::as_imm_buf(salt) |salt_buf, salt_len| { let mut out = vec::with_capacity(keylen); do vec::as_mut_buf(out) |out_buf, _out_len| { unsafe { let r = libcrypto::PKCS5_PBKDF2_HMAC_SHA1( pass_buf, pass_len as c_int, salt_buf, salt_len as c_int, iter as c_int, keylen as c_int, out_buf); if r != 1 as c_int { fail; } if r != 1 as c_int { fail!(); } } } unsafe { vec::raw::set_len(&mut out, keylen); } Loading @@ -40,11 +42,13 @@ pub fn pbkdf2_hmac_sha1(pass: &str, salt: &[u8], iter: uint, #[cfg(test)] mod tests { use super::*; // Test vectors from // http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 #[test] fn test_pbkdf2_hmac_sha1() { assert pbkdf2_hmac_sha1( assert!(pbkdf2_hmac_sha1( "password", str::to_bytes("salt"), 1u, Loading @@ -53,9 +57,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "password", str::to_bytes("salt"), 2u, Loading @@ -64,9 +68,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "password", str::to_bytes("salt"), 4096u, Loading @@ -75,9 +79,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "password", str::to_bytes("salt"), 16777216u, Loading @@ -86,9 +90,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "passwordPASSWORDpassword", str::to_bytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"), 4096u, Loading @@ -98,9 +102,9 @@ mod tests { 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!(pbkdf2_hmac_sha1( "pass\x00word", str::to_bytes("sa\x00lt"), 4096u, Loading @@ -109,6 +113,6 @@ mod tests { 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 ]; ]); } }
pkey.rs +215 −179 Original line number Diff line number Diff line use libc::{c_int, c_uint}; use core::libc::{c_int, c_uint}; use hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512}; #[allow(non_camel_case_types)] Loading Loading @@ -74,25 +74,33 @@ fn openssl_hash_nid(hash: HashType) -> c_int { } } fn rsa_to_any(rsa: *RSA) -> *ANYKEY unsafe { fn rsa_to_any(rsa: *RSA) -> *ANYKEY { unsafe { cast::reinterpret_cast(&rsa) } } fn any_to_rsa(anykey: *ANYKEY) -> *RSA unsafe { fn any_to_rsa(anykey: *ANYKEY) -> *RSA { unsafe { cast::reinterpret_cast(&anykey) } } pub struct PKey { priv mut evp: *EVP_PKEY, priv mut parts: Parts, priv evp: *EVP_PKEY, priv parts: Parts, } pub fn PKey() -> PKey { unsafe { PKey { evp: libcrypto::EVP_PKEY_new(), parts: Neither } } } ///Represents a public key, optionally with a private key attached. priv impl PKey { fn _tostr(f: fn@(*EVP_PKEY, &*mut u8) -> c_int) -> ~[u8] unsafe { priv fn _tostr(&self, f: @fn(*EVP_PKEY, &*mut u8) -> c_int) -> ~[u8] { unsafe { let buf = ptr::mut_null(); let len = f(self.evp, &buf); if len < 0 as c_int { return ~[]; } Loading @@ -102,13 +110,16 @@ priv impl PKey { f(self.evp, &ps) }; vec::slice(s, 0u, r as uint) vec::slice(s, 0u, r as uint).to_owned() } } fn _fromstr( priv fn _fromstr( &mut self, s: &[u8], f: fn@(c_int, &*EVP_PKEY, &*u8, c_uint) -> *EVP_PKEY ) unsafe { f: @fn(c_int, &*EVP_PKEY, &*u8, c_uint) -> *EVP_PKEY ) { unsafe { do vec::as_imm_buf(s) |ps, len| { let evp = ptr::null(); f(6 as c_int, &evp, &ps, len as c_uint); Loading @@ -116,10 +127,11 @@ priv impl PKey { } } } } ///Represents a public key, optionally with a private key attached. pub impl PKey { fn gen(keysz: uint) unsafe { fn gen(&mut self, keysz: uint) { unsafe { let rsa = libcrypto::RSA_generate_key( keysz as c_uint, 65537u as c_uint, Loading @@ -132,49 +144,60 @@ pub impl PKey { libcrypto::EVP_PKEY_assign(self.evp, 6 as c_int, rsa_); self.parts = Both; } } /** * Returns a serialized form of the public key, suitable for load_pub(). */ fn save_pub() -> ~[u8] { fn save_pub(&self) -> ~[u8] { unsafe { self._tostr(libcrypto::i2d_PublicKey) } } /** * Loads a serialized form of the public key, as produced by save_pub(). */ fn load_pub(s: &[u8]) { fn load_pub(&mut self, s: &[u8]) { unsafe { self._fromstr(s, libcrypto::d2i_PublicKey); self.parts = Public; } } /** * Returns a serialized form of the public and private keys, suitable for * load_priv(). */ fn save_priv() -> ~[u8] { fn save_priv(&self, ) -> ~[u8] { unsafe { self._tostr(libcrypto::i2d_PrivateKey) } } /** * Loads a serialized form of the public and private keys, as produced by * save_priv(). */ fn load_priv(s: &[u8]) { fn load_priv(&mut self, s: &[u8]) { unsafe { self._fromstr(s, libcrypto::d2i_PrivateKey); self.parts = Both; } } /** * Returns the size of the public key modulus. */ fn size() -> uint { fn size(&self) -> uint { unsafe { libcrypto::RSA_size(libcrypto::EVP_PKEY_get1_RSA(self.evp)) as uint } } /** * Returns whether this pkey object can perform the specified role. */ fn can(r: Role) -> bool { fn can(&self, r: Role) -> bool { match r { Encrypt => match self.parts { Loading Loading @@ -203,19 +226,22 @@ pub impl PKey { * Returns the maximum amount of data that can be encrypted by an encrypt() * call. */ fn max_data() -> uint unsafe { fn max_data(&self) -> uint { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let len = libcrypto::RSA_size(rsa); // 41 comes from RSA_public_encrypt(3) for OAEP len as uint - 41u } } fn encrypt_with_padding(s: &[u8], padding: EncryptionPadding) -> ~[u8] unsafe { fn encrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> ~[u8] { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let len = libcrypto::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); Loading @@ -232,17 +258,19 @@ pub impl PKey { if rv < 0 as c_int { ~[] } else { vec::slice(r, 0u, rv as uint) vec::const_slice(r, 0u, rv as uint).to_owned() } } } } } fn decrypt_with_padding(s: &[u8], padding: EncryptionPadding) -> ~[u8] unsafe { fn decrypt_with_padding(&self, s: &[u8], padding: EncryptionPadding) -> ~[u8] { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let len = libcrypto::RSA_size(rsa); assert s.len() as c_uint == libcrypto::RSA_size(rsa); assert!(s.len() as c_uint == libcrypto::RSA_size(rsa)); let mut r = vec::from_elem(len as uint + 1u, 0u8); Loading @@ -259,7 +287,8 @@ pub impl PKey { if rv < 0 as c_int { ~[] } else { vec::slice(r, 0u, rv as uint) vec::const_slice(r, 0u, rv as uint).to_owned() } } } } Loading @@ -269,26 +298,27 @@ pub impl PKey { * Encrypts data using OAEP padding, returning the encrypted data. The * supplied data must not be larger than max_data(). */ fn encrypt(s: &[u8]) -> ~[u8] unsafe { self.encrypt_with_padding(s, OAEP) } fn encrypt(&self, s: &[u8]) -> ~[u8] { unsafe { self.encrypt_with_padding(s, OAEP) } } /** * Decrypts data, expecting OAEP padding, returning the decrypted data. */ fn decrypt(s: &[u8]) -> ~[u8] unsafe { self.decrypt_with_padding(s, OAEP) } fn decrypt(&self, s: &[u8]) -> ~[u8] { unsafe { self.decrypt_with_padding(s, OAEP) } } /** * Signs data, using OpenSSL's default scheme and sha256. Unlike encrypt(), * can process an arbitrary amount of data; returns the signature. */ fn sign(s: &[u8]) -> ~[u8] unsafe { self.sign_with_hash(s, SHA256) } fn sign(&self, s: &[u8]) -> ~[u8] { unsafe { self.sign_with_hash(s, SHA256) } } /** * Verifies a signature s (using OpenSSL's default scheme and sha256) on a * message m. Returns true if the signature is valid, and false otherwise. */ fn verify(m: &[u8], s: &[u8]) -> bool unsafe { self.verify_with_hash(m, s, SHA256) } fn verify(&self, m: &[u8], s: &[u8]) -> bool { unsafe { self.verify_with_hash(m, s, SHA256) } } fn sign_with_hash(s: &[u8], hash: HashType) -> ~[u8] unsafe { fn sign_with_hash(&self, s: &[u8], hash: HashType) -> ~[u8] { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); let len = libcrypto::RSA_size(rsa); let mut r = vec::from_elem(len as uint + 1u, 0u8); Loading @@ -308,13 +338,15 @@ pub impl PKey { if rv < 0 as c_int { ~[] } else { vec::slice(r, 0u, *plen as uint) vec::const_slice(r, 0u, *plen as uint).to_owned() } } } } } fn verify_with_hash(m: &[u8], s: &[u8], hash: HashType) -> bool unsafe { fn verify_with_hash(&self, m: &[u8], s: &[u8], hash: HashType) -> bool { unsafe { let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); do vec::as_imm_buf(m) |pm, m_len| { Loading @@ -333,93 +365,97 @@ pub impl PKey { } } } } #[cfg(test)] mod tests { use super::*; use hash::{MD5, SHA1}; #[test] fn test_gen_pub() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); k0.gen(512u); k1.load_pub(k0.save_pub()); assert(k0.save_pub() == k1.save_pub()); assert(k0.size() == k1.size()); assert(k0.can(Encrypt)); assert(k0.can(Decrypt)); assert(k0.can(Verify)); assert(k0.can(Sign)); assert(k1.can(Encrypt)); assert(!k1.can(Decrypt)); assert(k1.can(Verify)); assert(!k1.can(Sign)); assert!(k0.save_pub() == k1.save_pub()); assert!(k0.size() == k1.size()); assert!(k0.can(Encrypt)); assert!(k0.can(Decrypt)); assert!(k0.can(Verify)); assert!(k0.can(Sign)); assert!(k1.can(Encrypt)); assert!(!k1.can(Decrypt)); assert!(k1.can(Verify)); assert!(!k1.can(Sign)); } #[test] fn test_gen_priv() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); k0.gen(512u); k1.load_priv(k0.save_priv()); assert(k0.save_priv() == k1.save_priv()); assert(k0.size() == k1.size()); assert(k0.can(Encrypt)); assert(k0.can(Decrypt)); assert(k0.can(Verify)); assert(k0.can(Sign)); assert(k1.can(Encrypt)); assert(k1.can(Decrypt)); assert(k1.can(Verify)); assert(k1.can(Sign)); assert!(k0.save_priv() == k1.save_priv()); assert!(k0.size() == k1.size()); assert!(k0.can(Encrypt)); assert!(k0.can(Decrypt)); assert!(k0.can(Verify)); assert!(k0.can(Sign)); assert!(k1.can(Encrypt)); assert!(k1.can(Decrypt)); assert!(k1.can(Verify)); assert!(k1.can(Sign)); } #[test] fn test_encrypt() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; k0.gen(512u); k1.load_pub(k0.save_pub()); let emsg = k1.encrypt(msg); let dmsg = k0.decrypt(emsg); assert(msg == dmsg); assert!(msg == dmsg); } #[test] fn test_encrypt_pkcs() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; k0.gen(512u); k1.load_pub(k0.save_pub()); let emsg = k1.encrypt_with_padding(msg, PKCS1v15); let dmsg = k0.decrypt_with_padding(emsg, PKCS1v15); assert(msg == dmsg); assert!(msg == dmsg); } #[test] fn test_sign() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; k0.gen(512u); k1.load_pub(k0.save_pub()); let sig = k0.sign(msg); let rv = k1.verify(msg, sig); assert(rv == true); assert!(rv == true); } #[test] fn test_sign_hashes() { let k0 = PKey(); let k1 = PKey(); let mut k0 = PKey(); let mut k1 = PKey(); let msg = ~[0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; k0.gen(512u); k1.load_pub(k0.save_pub()); let sig = k0.sign_with_hash(msg, MD5); assert k1.verify_with_hash(msg, sig, MD5); assert !k1.verify_with_hash(msg, sig, SHA1); assert!(k1.verify_with_hash(msg, sig, MD5)); assert!(!k1.verify_with_hash(msg, sig, SHA1)); } }