diff options
| author | Erick Tryzelaar <[email protected]> | 2013-12-18 08:51:10 -0800 |
|---|---|---|
| committer | Erick Tryzelaar <[email protected]> | 2013-12-18 08:51:10 -0800 |
| commit | a9ce2a36d54ac08608d689a5f0ec441f74e56d61 (patch) | |
| tree | 813ceb833817cfac21a1cc920446f8a7927acf76 /src | |
| parent | Update to rust 0.9x-pre (diff) | |
| download | rust-openssl-a9ce2a36d54ac08608d689a5f0ec441f74e56d61.tar.xz rust-openssl-a9ce2a36d54ac08608d689a5f0ec441f74e56d61.zip | |
Switch over to rustpkg
Diffstat (limited to 'src')
| -rw-r--r-- | src/crypto/hash.rs | 187 | ||||
| -rw-r--r-- | src/crypto/hex.rs | 87 | ||||
| -rw-r--r-- | src/crypto/hmac.rs | 87 | ||||
| -rw-r--r-- | src/crypto/lib.rs | 32 | ||||
| -rw-r--r-- | src/crypto/pkcs5.rs | 138 | ||||
| -rw-r--r-- | src/crypto/pkey.rs | 451 | ||||
| -rw-r--r-- | src/crypto/rand.rs | 35 | ||||
| -rw-r--r-- | src/crypto/symm.rs | 296 |
8 files changed, 1313 insertions, 0 deletions
diff --git a/src/crypto/hash.rs b/src/crypto/hash.rs new file mode 100644 index 00000000..339aafeb --- /dev/null +++ b/src/crypto/hash.rs @@ -0,0 +1,187 @@ +use std::libc::c_uint; +use std::libc; +use std::ptr; +use std::vec; + +pub enum HashType { + MD5, + SHA1, + SHA224, + SHA256, + SHA384, + SHA512 +} + +#[allow(non_camel_case_types)] +pub type EVP_MD_CTX = *libc::c_void; + +#[allow(non_camel_case_types)] +pub type EVP_MD = *libc::c_void; + +mod libcrypto { + use super::*; + use std::libc::c_uint; + + #[link(name = "crypto")] + extern { + pub fn EVP_MD_CTX_create() -> EVP_MD_CTX; + pub fn EVP_MD_CTX_destroy(ctx: EVP_MD_CTX); + + pub fn EVP_md5() -> EVP_MD; + pub fn EVP_sha1() -> EVP_MD; + pub fn EVP_sha224() -> EVP_MD; + 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) { + unsafe { + match t { + MD5 => (libcrypto::EVP_md5(), 16u), + SHA1 => (libcrypto::EVP_sha1(), 20u), + SHA224 => (libcrypto::EVP_sha224(), 28u), + SHA256 => (libcrypto::EVP_sha256(), 32u), + SHA384 => (libcrypto::EVP_sha384(), 48u), + SHA512 => (libcrypto::EVP_sha512(), 64u), + } + } +} + +pub struct Hasher { + priv evp: EVP_MD, + priv ctx: EVP_MD_CTX, + priv len: uint, +} + +impl Hasher { + pub fn new(ht: HashType) -> Hasher { + let ctx = unsafe { libcrypto::EVP_MD_CTX_create() }; + let (evp, mdlen) = evpmd(ht); + unsafe { + libcrypto::EVP_DigestInit(ctx, evp); + } + + Hasher { evp: evp, ctx: ctx, len: mdlen } + } + + /// Update this hasher with more input bytes + pub fn update(&self, data: &[u8]) { + data.as_imm_buf(|pdata, len| { + unsafe { + libcrypto::EVP_DigestUpdate(self.ctx, pdata, len as c_uint) + } + }); + } + + /** + * Return the digest of all bytes added to this hasher since its last + * initialization + */ + pub fn final(&self) -> ~[u8] { + let mut res = vec::from_elem(self.len, 0u8); + res.as_mut_buf(|pres, _len| { + unsafe { + libcrypto::EVP_DigestFinal(self.ctx, pres, ptr::null()); + } + }); + res + } +} + +impl Drop for Hasher { + fn drop(&mut self) { + unsafe { + libcrypto::EVP_MD_CTX_destroy(self.ctx); + } + } +} + +/** + * Hashes the supplied input data using hash t, returning the resulting hash + * value + */ +pub fn hash(t: HashType, data: &[u8]) -> ~[u8] { + let h = Hasher::new(t); + h.update(data); + h.final() +} + +#[cfg(test)] +mod tests { + use super::*; + use hex::FromHex; + use hex::ToHex; + + struct HashTest { + input: ~[u8], + expected_output: ~str + } + + fn HashTest(input: ~str, output: ~str) -> HashTest { + HashTest { input: input.from_hex(), + expected_output: output } + } + + fn hash_test(hashtype: HashType, hashtest: &HashTest) { + let calced_raw = hash(hashtype, hashtest.input); + + let calced = calced_raw.to_hex(); + + if calced != hashtest.expected_output { + println!("Test failed - {} != {}", calced, hashtest.expected_output); + } + + assert!(calced == hashtest.expected_output); + } + + // Test vectors from http://www.nsrl.nist.gov/testdata/ + #[test] + fn test_md5() { + let tests = [ + HashTest(~"", ~"D41D8CD98F00B204E9800998ECF8427E"), + HashTest(~"7F", ~"83ACB6E67E50E31DB6ED341DD2DE1595"), + HashTest(~"EC9C", ~"0B07F0D4CA797D8AC58874F887CB0B68"), + HashTest(~"FEE57A", ~"E0D583171EB06D56198FC0EF22173907"), + HashTest(~"42F497E0", ~"7C430F178AEFDF1487FEE7144E9641E2"), + HashTest(~"C53B777F1C", ~"75EF141D64CB37EC423DA2D9D440C925"), + HashTest(~"89D5B576327B", ~"EBBAF15EB0ED784C6FAA9DC32831BF33"), + HashTest(~"5D4CCE781EB190", ~"CE175C4B08172019F05E6B5279889F2C"), + HashTest(~"81901FE94932D7B9", ~"CD4D2F62B8CDB3A0CF968A735A239281"), + HashTest(~"C9FFDEE7788EFB4EC9", ~"E0841A231AB698DB30C6C0F3F246C014"), + HashTest(~"66AC4B7EBA95E53DC10B", ~"A3B3CEA71910D9AF56742AA0BB2FE329"), + HashTest(~"A510CD18F7A56852EB0319", ~"577E216843DD11573574D3FB209B97D8"), + HashTest(~"AAED18DBE8938C19ED734A8D", ~"6F80FB775F27E0A4CE5C2F42FC72C5F1")]; + + for test in tests.iter() { + hash_test(MD5, test); + } + } + + #[test] + fn test_sha1() { + let tests = [ + HashTest(~"616263", ~"A9993E364706816ABA3E25717850C26C9CD0D89D"), + ]; + + for test in tests.iter() { + hash_test(SHA1, test); + } + } + + #[test] + fn test_sha256() { + let tests = [ + HashTest(~"616263", ~"BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD") + ]; + + for test in tests.iter() { + hash_test(SHA256, test); + } + } +} diff --git a/src/crypto/hex.rs b/src/crypto/hex.rs new file mode 100644 index 00000000..f55dc1a9 --- /dev/null +++ b/src/crypto/hex.rs @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Jack Lloyd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use std::vec; + +pub trait ToHex { + fn to_hex(&self) -> ~str; +} + +impl<'a> ToHex for &'a [u8] { + fn to_hex(&self) -> ~str { + + let chars = "0123456789ABCDEF".chars().collect::<~[char]>(); + + let mut s = ~""; + + for i in range(0u, self.len()) { + + let x = self[i]; + + let xhi = (x >> 4) & 0x0F; + let xlo = (x ) & 0x0F; + + s.push_char(chars[xhi]); + s.push_char(chars[xlo]); + } + + s + } +} + +pub trait FromHex { + fn from_hex(&self) -> ~[u8]; +} + +impl<'a> FromHex for &'a str { + fn from_hex(&self) -> ~[u8] { + let mut vec = vec::with_capacity(self.len() / 2); + + for (i,c) in self.chars().enumerate() { + 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"); }; + + if i % 2 == 0 { + vec.push(nibble << 4); + } + else { + vec[i/2] |= nibble; + } + } + + vec + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + pub fn test() { + + assert!([05u8, 0xffu8, 0x00u8, 0x59u8].to_hex() == ~"05FF0059"); + + assert!("00FFA9D1F5".from_hex() == ~[0, 0xff, 0xa9, 0xd1, 0xf5]); + + assert!("00FFA9D1F5".from_hex().to_hex() == ~"00FFA9D1F5"); + } + + +} diff --git a/src/crypto/hmac.rs b/src/crypto/hmac.rs new file mode 100644 index 00000000..5bc8b359 --- /dev/null +++ b/src/crypto/hmac.rs @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Jack Lloyd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use hash::*; +use std::{libc,ptr,vec}; + +#[allow(non_camel_case_types)] +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")] +extern { + fn HMAC_CTX_init(ctx: *mut HMAC_CTX, key: *u8, keylen: libc::c_int, md: EVP_MD); + + 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 libc::c_uint); +} + +pub struct HMAC { + priv ctx: HMAC_CTX, + priv len: uint, +} + +pub fn HMAC(ht: HashType, key: ~[u8]) -> HMAC { + unsafe { + + let (evp, mdlen) = evpmd(ht); + + let mut ctx : HMAC_CTX = HMAC_CTX { + md: ptr::null(), + md_ctx: ptr::null(), + i_ctx: ptr::null(), + o_ctx: ptr::null(), + key_length: 0, + key: [0u8, .. 128] + }; + + HMAC_CTX_init(&mut ctx, + key.as_ptr(), + key.len() as libc::c_int, + evp); + + HMAC { ctx: ctx, len: mdlen } + } +} + +impl HMAC { + pub fn update(&mut self, data: &[u8]) { + unsafe { + data.as_imm_buf(|pdata, len| { + HMAC_Update(&mut self.ctx, pdata, len as libc::c_uint) + }); + } + } + + pub fn final(&mut self) -> ~[u8] { + unsafe { + let mut res = vec::from_elem(self.len, 0u8); + let mut outlen: libc::c_uint = 0; + res.as_mut_buf(|pres, _len| { + HMAC_Final(&mut self.ctx, pres, &mut outlen); + assert!(self.len == outlen as uint) + }); + res + } + } +} diff --git a/src/crypto/lib.rs b/src/crypto/lib.rs new file mode 100644 index 00000000..7ed4bfd9 --- /dev/null +++ b/src/crypto/lib.rs @@ -0,0 +1,32 @@ +/* + * Copyright 2011 Google Inc. + * 2013 Jack Lloyd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#[link(name = "crypto", + package_id = "crypto", + vers = "0.3", + uuid = "38297409-b4c2-4499-8131-a99a7e44dad3")]; +#[crate_type = "lib"]; + +#[feature(globs)]; + +pub mod hash; +pub mod hex; +pub mod hmac; +pub mod pkcs5; +pub mod pkey; +pub mod rand; +pub mod symm; diff --git a/src/crypto/pkcs5.rs b/src/crypto/pkcs5.rs new file mode 100644 index 00000000..9dfc026c --- /dev/null +++ b/src/crypto/pkcs5.rs @@ -0,0 +1,138 @@ +use std::libc::c_int; +use std::vec; + +mod libcrypto { + use std::libc::c_int; + + #[link(name = "crypto")] + extern { + pub fn PKCS5_PBKDF2_HMAC_SHA1(pass: *u8, passlen: 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. +pub fn pbkdf2_hmac_sha1(pass: &str, salt: &[u8], iter: uint, + keylen: uint) -> ~[u8] { + assert!(iter >= 1u); + assert!(keylen >= 1u); + + pass.as_imm_buf(|pass_buf, pass_len| { + 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 = unsafe { + 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!(); } + }); + + unsafe { out.set_len(keylen); } + + out + }) + }) +} + +#[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_eq!( + pbkdf2_hmac_sha1( + "password", + "salt".as_bytes(), + 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 + ] + ); + + assert_eq!( + pbkdf2_hmac_sha1( + "password", + "salt".as_bytes(), + 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 + ] + ); + + assert_eq!( + pbkdf2_hmac_sha1( + "password", + "salt".as_bytes(), + 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 + ] + ); + + assert_eq!( + pbkdf2_hmac_sha1( + "password", + "salt".as_bytes(), + 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 + ] + ); + + assert_eq!( + pbkdf2_hmac_sha1( + "passwordPASSWORDpassword", + "saltSALTsaltSALTsaltSALTsaltSALTsalt".as_bytes(), + 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, + 0xf2_u8, 0xf0_u8, 0x70_u8, 0x38_u8 + ] + ); + + assert_eq!( + pbkdf2_hmac_sha1( + "pass\x00word", + "sa\x00lt".as_bytes(), + 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 + ] + ); + } +} diff --git a/src/crypto/pkey.rs b/src/crypto/pkey.rs new file mode 100644 index 00000000..7b5245b2 --- /dev/null +++ b/src/crypto/pkey.rs @@ -0,0 +1,451 @@ +use std::cast; +use std::libc::{c_int, c_uint}; +use std::libc; +use std::ptr; +use std::vec; +use hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512}; + +#[allow(non_camel_case_types)] +pub type EVP_PKEY = *libc::c_void; + +#[allow(non_camel_case_types)] +pub type RSA = *libc::c_void; + +mod libcrypto { + use super::*; + use std::libc::{c_char, c_int, c_uint}; + + #[link(name = "crypto")] + extern { + pub fn EVP_PKEY_new() -> *EVP_PKEY; + pub fn EVP_PKEY_free(k: *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; + pub fn d2i_PublicKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY; + 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; + pub fn RSA_size(k: *RSA) -> c_uint; + + pub fn RSA_public_encrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA, + pad: c_int) -> c_int; + pub fn RSA_private_decrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA, + pad: c_int) -> c_int; + pub fn RSA_sign(t: c_int, m: *u8, mlen: c_uint, sig: *mut u8, siglen: *mut c_uint, + 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 { + Neither, + Public, + Both +} + +/// Represents a role an asymmetric key might be appropriate for. +pub enum Role { + Encrypt, + Decrypt, + Sign, + Verify +} + +/// Type of encryption padding to use. +pub enum EncryptionPadding { + OAEP, + PKCS1v15 +} + +fn openssl_padding_code(padding: EncryptionPadding) -> c_int { + match padding { + OAEP => 4, + PKCS1v15 => 1 + } +} + +fn openssl_hash_nid(hash: HashType) -> c_int { + match hash { + MD5 => 4, // NID_md5, + SHA1 => 64, // NID_sha1 + SHA224 => 675, // NID_sha224 + SHA256 => 672, // NID_sha256 + SHA384 => 673, // NID_sha384 + SHA512 => 674, // NID_sha512 + } +} + +pub struct PKey { + priv evp: *EVP_PKEY, + priv parts: Parts, +} + +/// Represents a public key, optionally with a private key attached. +impl PKey { + pub fn new() -> PKey { + PKey { + evp: unsafe { libcrypto::EVP_PKEY_new() }, + parts: Neither, + } + } + + fn _tostr(&self, f: extern "C" unsafe fn(*EVP_PKEY, **mut u8) -> c_int) -> ~[u8] { + unsafe { + let len = f(self.evp, ptr::null()); + if len < 0 as c_int { return ~[]; } + let mut s = vec::from_elem(len as uint, 0u8); + + let r = 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) { + s.as_imm_buf(|ps, len| { + let evp = ptr::null(); + unsafe { + f(6 as c_int, &evp, &ps, len as c_uint); + } + self.evp = evp; + }); + } + + pub fn gen(&mut self, keysz: uint) { + unsafe { + let rsa = libcrypto::RSA_generate_key( + keysz as c_uint, + 65537u as c_uint, + ptr::null(), + ptr::null() + ); + + // XXX: 6 == NID_rsaEncryption + libcrypto::EVP_PKEY_assign( + self.evp, + 6 as c_int, + cast::transmute(rsa)); + + self.parts = Both; + } + } + + /** + * Returns a serialized form of the public key, suitable for load_pub(). + */ + pub fn save_pub(&self) -> ~[u8] { + self._tostr(libcrypto::i2d_PublicKey) + } + + /** + * Loads a serialized form of the public key, as produced by save_pub(). + */ + pub fn load_pub(&mut self, s: &[u8]) { + self._fromstr(s, libcrypto::d2i_PublicKey); + self.parts = Public; + } + + /** + * Returns a serialized form of the public and private keys, suitable for + * load_priv(). + */ + pub fn save_priv(&self) -> ~[u8] { + self._tostr(libcrypto::i2d_PrivateKey) + } + /** + * Loads a serialized form of the public and private keys, as produced by + * save_priv(). + */ + pub fn load_priv(&mut self, s: &[u8]) { + self._fromstr(s, libcrypto::d2i_PrivateKey); + self.parts = Both; + } + + /** + * Returns the size of the public key modulus. + */ + pub 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. + */ + pub fn can(&self, r: Role) -> bool { + match r { + Encrypt => + match self.parts { + Neither => false, + _ => true, + }, + Verify => + match self.parts { + Neither => false, + _ => true, + }, + Decrypt => + match self.parts { + Both => true, + _ => false, + }, + Sign => + match self.parts { + Both => true, + _ => false, + }, + } + } + + /** + * Returns the maximum amount of data that can be encrypted by an encrypt() + * call. + */ + pub 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 + } + } + + pub 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()); + + let mut r = vec::from_elem(len as uint + 1u, 0u8); + + let rv = r.as_mut_buf(|pr, _len| { + s.as_imm_buf(|ps, s_len| { + libcrypto::RSA_public_encrypt( + s_len as c_uint, + ps, + pr, + rsa, + openssl_padding_code(padding) + ) + }) + }); + if rv < 0 as c_int { + ~[] + } else { + r.truncate(rv as uint); + r + } + } + } + + pub 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_eq!(s.len() as c_uint, libcrypto::RSA_size(rsa)); + + let mut r = vec::from_elem(len as uint + 1u, 0u8); + + let rv = r.as_mut_buf(|pr, _len| { + s.as_imm_buf(|ps, s_len| { + libcrypto::RSA_private_decrypt( + s_len as c_uint, + ps, + pr, + rsa, + openssl_padding_code(padding) + ) + }) + }); + + if rv < 0 as c_int { + ~[] + } else { + r.truncate(rv as uint); + r + } + } + } + + /** + * Encrypts data using OAEP padding, returning the encrypted data. The + * supplied data must not be larger than max_data(). + */ + pub fn encrypt(&self, s: &[u8]) -> ~[u8] { self.encrypt_with_padding(s, OAEP) } + + /** + * Decrypts data, expecting OAEP padding, returning the decrypted data. + */ + pub fn decrypt(&self, s: &[u8]) -> ~[u8] { 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. + */ + pub fn sign(&self, s: &[u8]) -> ~[u8] { 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. + */ + pub fn verify(&self, m: &[u8], s: &[u8]) -> bool { self.verify_with_hash(m, s, SHA256) } + + pub fn sign_with_hash(&self, s: &[u8], hash: HashType) -> ~[u8] { + unsafe { + let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); + let mut len = libcrypto::RSA_size(rsa); + let mut r = vec::from_elem(len as uint + 1u, 0u8); + + let rv = r.as_mut_buf(|pr, _len| { + s.as_imm_buf(|ps, s_len| { + libcrypto::RSA_sign( + openssl_hash_nid(hash), + ps, + s_len as c_uint, + pr, + &mut len, + rsa) + }) + }); + + if rv < 0 as c_int { + ~[] + } else { + r.truncate(len as uint); + r + } + } + } + + pub fn verify_with_hash(&self, m: &[u8], s: &[u8], hash: HashType) -> bool { + unsafe { + let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp); + + m.as_imm_buf(|pm, m_len| { + s.as_imm_buf(|ps, s_len| { + let rv = libcrypto::RSA_verify( + openssl_hash_nid(hash), + pm, + m_len as c_uint, + ps, + s_len as c_uint, + rsa + ); + + rv == 1 as c_int + }) + }) + } + } +} + +impl Drop for PKey { + fn drop(&mut self) { + unsafe { + libcrypto::EVP_PKEY_free(self.evp); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use hash::{MD5, SHA1}; + + #[test] + fn test_gen_pub() { + let mut k0 = PKey::new(); + let mut k1 = PKey::new(); + 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)); + } + + #[test] + fn test_gen_priv() { + let mut k0 = PKey::new(); + let mut k1 = PKey::new(); + 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)); + } + + #[test] + fn test_encrypt() { + let mut k0 = PKey::new(); + let mut k1 = PKey::new(); + 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); + } + + #[test] + fn test_encrypt_pkcs() { + let mut k0 = PKey::new(); + let mut k1 = PKey::new(); + 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); + } + + #[test] + fn test_sign() { + let mut k0 = PKey::new(); + let mut k1 = PKey::new(); + 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); + } + + #[test] + fn test_sign_hashes() { + let mut k0 = PKey::new(); + let mut k1 = PKey::new(); + 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)); + } +} diff --git a/src/crypto/rand.rs b/src/crypto/rand.rs new file mode 100644 index 00000000..6510b9f4 --- /dev/null +++ b/src/crypto/rand.rs @@ -0,0 +1,35 @@ +use std::libc::c_int; +use std::vec; + +mod libcrypto { + use std::libc::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] { + let mut out = vec::with_capacity(len); + + out.as_mut_buf(|out_buf, len| { + let r = unsafe { libcrypto::RAND_bytes(out_buf, len as c_int) }; + if r != 1 as c_int { fail!() } + }); + + unsafe { out.set_len(len); } + + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_rand_bytes() { + let bytes = rand_bytes(32u); + println!("{:?}", bytes); + } +} diff --git a/src/crypto/symm.rs b/src/crypto/symm.rs new file mode 100644 index 00000000..3d31bde0 --- /dev/null +++ b/src/crypto/symm.rs @@ -0,0 +1,296 @@ +use std::libc::c_int; +use std::libc; +use std::vec; + +#[allow(non_camel_case_types)] +pub type EVP_CIPHER_CTX = *libc::c_void; + +#[allow(non_camel_case_types)] +pub type EVP_CIPHER = *libc::c_void; + +mod libcrypto { + use super::*; + use std::libc::{c_int, c_uint}; + + extern { + #[link_args = "-lcrypto"] + pub fn EVP_CIPHER_CTX_new() -> EVP_CIPHER_CTX; + pub fn EVP_CIPHER_CTX_set_padding(ctx: EVP_CIPHER_CTX, padding: c_int); + pub fn EVP_CIPHER_CTX_free(ctx: EVP_CIPHER_CTX); + + pub fn EVP_aes_128_ecb() -> EVP_CIPHER; + pub fn EVP_aes_128_cbc() -> EVP_CIPHER; + // pub fn EVP_aes_128_ctr() -> EVP_CIPHER; + // pub fn EVP_aes_128_gcm() -> EVP_CIPHER; + + pub fn EVP_aes_256_ecb() -> 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; + + pub fn EVP_CipherInit(ctx: EVP_CIPHER_CTX, evp: EVP_CIPHER, + key: *u8, iv: *u8, mode: c_int); + pub fn EVP_CipherUpdate(ctx: EVP_CIPHER_CTX, outbuf: *mut u8, + 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 { + Encrypt, + Decrypt, +} + +#[allow(non_camel_case_types)] +pub enum Type { + AES_128_ECB, + AES_128_CBC, + // AES_128_CTR, + //AES_128_GCM, + + AES_256_ECB, + AES_256_CBC, + // AES_256_CTR, + //AES_256_GCM, + + RC4_128, +} + +fn evpc(t: Type) -> (EVP_CIPHER, uint, uint) { + unsafe { + match t { + AES_128_ECB => (libcrypto::EVP_aes_128_ecb(), 16u, 16u), + AES_128_CBC => (libcrypto::EVP_aes_128_cbc(), 16u, 16u), + // AES_128_CTR => (libcrypto::EVP_aes_128_ctr(), 16u, 0u), + //AES_128_GCM => (libcrypto::EVP_aes_128_gcm(), 16u, 16u), + + AES_256_ECB => (libcrypto::EVP_aes_256_ecb(), 32u, 16u), + AES_256_CBC => (libcrypto::EVP_aes_256_cbc(), 32u, 16u), + // AES_256_CTR => (libcrypto::EVP_aes_256_ctr(), 32u, 0u), + //AES_256_GCM => (libcrypto::EVP_aes_256_gcm(), 32u, 16u), + + RC4_128 => (libcrypto::EVP_rc4(), 16u, 0u), + } + } +} + +/// Represents a symmetric cipher context. +pub struct Crypter { + priv evp: EVP_CIPHER, + priv ctx: EVP_CIPHER_CTX, + priv keylen: uint, + priv blocksize: uint +} + +impl Crypter { + pub fn new(t: Type) -> Crypter { + let ctx = unsafe { libcrypto::EVP_CIPHER_CTX_new() }; + let (evp, keylen, blocksz) = evpc(t); + Crypter { evp: evp, ctx: ctx, keylen: keylen, blocksize: blocksz } + } + + /** + * Enables or disables padding. If padding is disabled, total amount of + * data encrypted must be a multiple of block size. + */ + pub fn pad(&self, padding: bool) { + if self.blocksize > 0 { + unsafe { + let v = if padding { 1 } else { 0 } as c_int; + libcrypto::EVP_CIPHER_CTX_set_padding(self.ctx, v); + } + } + } + + /** + * Initializes this crypter. + */ + pub fn init(&self, mode: Mode, key: &[u8], iv: &[u8]) { + unsafe { + let mode = match mode { + Encrypt => 1 as c_int, + Decrypt => 0 as c_int, + }; + assert_eq!(key.len(), self.keylen); + + key.as_imm_buf(|pkey, _len| { + iv.as_imm_buf(|piv, _len| { + libcrypto::EVP_CipherInit( + self.ctx, + self.evp, + pkey, + piv, + mode + ) + }); + }); + } + } + + /** + * Update this crypter with more data to encrypt or decrypt. Returns + * encrypted or decrypted bytes. + */ + pub fn update(&self, data: &[u8]) -> ~[u8] { + unsafe { + data.as_imm_buf(|pdata, len| { + let mut res = vec::from_elem(len + self.blocksize, 0u8); + + let reslen = res.as_mut_buf(|pres, _len| { + let mut reslen = (len + self.blocksize) as u32; + + libcrypto::EVP_CipherUpdate( + self.ctx, + pres, + &mut reslen, + pdata, + len as c_int + ); + + reslen + }); + + res.truncate(reslen as uint); + res + }) + } + } + + /** + * Finish crypting. Returns the remaining partial block of output, if any. + */ + pub fn final(&self) -> ~[u8] { + unsafe { + let mut res = vec::from_elem(self.blocksize, 0u8); + + let reslen = res.as_mut_buf(|pres, _len| { + let mut reslen = self.blocksize as c_int; + libcrypto::EVP_CipherFinal(self.ctx, pres, &mut reslen); + reslen + }); + + res.truncate(reslen as uint); + res + } + } +} + +impl Drop for Crypter { + fn drop(&mut self) { + unsafe { + libcrypto::EVP_CIPHER_CTX_free(self.ctx); + } + } +} + +/** + * Encrypts data, using the specified crypter type in encrypt mode with the + * specified key and iv; returns the resulting (encrypted) data. + */ +pub fn encrypt(t: Type, key: &[u8], iv: ~[u8], data: &[u8]) -> ~[u8] { + let c = Crypter::new(t); + c.init(Encrypt, key, iv); + let r = c.update(data); + let rest = c.final(); + r + rest +} + +/** + * Decrypts data, using the specified crypter type in decrypt mode with the + * specified key and iv; returns the resulting (decrypted) data. + */ +pub fn decrypt(t: Type, key: &[u8], iv: ~[u8], data: &[u8]) -> ~[u8] { + let c = Crypter::new(t); + c.init(Decrypt, key, iv); + let r = c.update(data); + let rest = c.final(); + r + rest +} + +#[cfg(test)] +mod tests { + use super::*; + + use hex::FromHex; + + // Test vectors from FIPS-197: + // http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf + #[test] + fn test_aes_256_ecb() { + let k0 = + ~[ 0x00u8, 0x01u8, 0x02u8, 0x03u8, 0x04u8, 0x05u8, 0x06u8, 0x07u8, + 0x08u8, 0x09u8, 0x0au8, 0x0bu8, 0x0cu8, 0x0du8, 0x0eu8, 0x0fu8, + 0x10u8, 0x11u8, 0x12u8, 0x13u8, 0x14u8, 0x15u8, 0x16u8, 0x17u8, + 0x18u8, 0x19u8, 0x1au8, 0x1bu8, 0x1cu8, 0x1du8, 0x1eu8, 0x1fu8 ]; + let p0 = + ~[ 0x00u8, 0x11u8, 0x22u8, 0x33u8, 0x44u8, 0x55u8, 0x66u8, 0x77u8, + 0x88u8, 0x99u8, 0xaau8, 0xbbu8, 0xccu8, 0xddu8, 0xeeu8, 0xffu8 ]; + let c0 = + ~[ 0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8, + 0xeau8, 0xfcu8, 0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8 ]; + let c = Crypter::new(AES_256_ECB); + c.init(Encrypt, k0, []); + c.pad(false); + let r0 = c.update(p0) + c.final(); + assert!(r0 == c0); + c.init(Decrypt, k0, []); + c.pad(false); + let p1 = c.update(r0) + c.final(); + assert!(p1 == p0); + } + + fn cipher_test(ciphertype: Type, pt: ~str, ct: ~str, key: ~str, iv: ~str) { + use hex::ToHex; + + let cipher = Crypter::new(ciphertype); + cipher.init(Encrypt, key.from_hex(), iv.from_hex()); + + let expected = ct.from_hex(); + let computed = cipher.update(pt.from_hex()) + cipher.final(); + + if computed != expected { + println!("Computed: {}", computed.to_hex()); + println!("Expected: {}", expected.to_hex()); + if computed.len() != expected.len() { + println!("Lengths differ: {} in computed vs {} expected", + computed.len(), expected.len()); + } + fail!("test failure"); + } + } + + #[test] + fn test_rc4() { + + let pt = ~"0000000000000000000000000000000000000000000000000000000000000000000000000000"; + let ct = ~"A68686B04D686AA107BD8D4CAB191A3EEC0A6294BC78B60F65C25CB47BD7BB3A48EFC4D26BE4"; + let key = ~"97CD440324DA5FD1F7955C1C13B6B466"; + let iv = ~""; + + cipher_test(RC4_128, pt, ct, key, iv); + } + + /*#[test] + fn test_aes128_ctr() { + + let pt = ~"6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710"; + let ct = ~"874D6191B620E3261BEF6864990DB6CE9806F66B7970FDFF8617187BB9FFFDFF5AE4DF3EDBD5D35E5B4F09020DB03EAB1E031DDA2FBE03D1792170A0F3009CEE"; + let key = ~"2B7E151628AED2A6ABF7158809CF4F3C"; + let iv = ~"F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; + + cipher_test(AES_128_CTR, pt, ct, key, iv); + }*/ + + /*#[test] + fn test_aes128_gcm() { + // Test case 3 in GCM spec + let pt = ~"d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255"; + let ct = ~"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f59854d5c2af327cd64a62cf35abd2ba6fab4"; + let key = ~"feffe9928665731c6d6a8f9467308308"; + let iv = ~"cafebabefacedbaddecaf888"; + + cipher_test(AES_128_GCM, pt, ct, key, iv); + }*/ +} |