Commit e3fef0c4 authored by Erick Tryzelaar's avatar Erick Tryzelaar
Browse files

Update to rust 0.8-pre

parent 3ed6d865
Loading
Loading
Loading
Loading
+0 −2
Original line number Diff line number Diff line
@@ -19,8 +19,6 @@
       uuid = "38297409-b4c2-4499-8131-a99a7e44dad3")];
#[crate_type = "lib"];

extern mod std; // FIXME https://github.com/mozilla/rust/issues/1127

pub mod hash;
pub mod pkey;
pub mod symm;
+55 −40
Original line number Diff line number Diff line
use libc::c_uint;
use std::libc::c_uint;
use std::libc;
use std::ptr;
use std::vec;

pub enum HashType {
    MD5,
@@ -10,14 +13,17 @@ 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"]
extern mod libcrypto {
mod libcrypto {
    use super::*;
    use std::libc::c_uint;

    #[link_args = "-lcrypto"]
    extern {
        fn EVP_MD_CTX_create() -> EVP_MD_CTX;

        fn EVP_md5() -> EVP_MD;
@@ -31,8 +37,10 @@ extern mod libcrypto {
        fn EVP_DigestUpdate(ctx: EVP_MD_CTX, data: *u8, n: c_uint);
        fn EVP_DigestFinal(ctx: EVP_MD_CTX, res: *mut u8, n: *u32);
    }
}

fn evpmd(t: HashType) -> (EVP_MD, uint) {
    unsafe {
        match t {
            MD5 => (libcrypto::EVP_md5(), 16u),
            SHA1 => (libcrypto::EVP_sha1(), 20u),
@@ -42,6 +50,7 @@ fn evpmd(t: HashType) -> (EVP_MD, uint) {
            SHA512 => (libcrypto::EVP_sha512(), 64u),
        }
    }
}

pub struct Hasher {
    priv evp: EVP_MD,
@@ -50,35 +59,39 @@ pub struct Hasher {
}

pub fn Hasher(ht: HashType) -> Hasher {
    let ctx = libcrypto::EVP_MD_CTX_create();
    let ctx = unsafe { 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 {
impl Hasher {
    /// Initializes this hasher
    fn init() unsafe {
        libcrypto::EVP_DigestInit(self.ctx, self.evp);
    pub fn init(&self) {
        unsafe { libcrypto::EVP_DigestInit(self.ctx, self.evp) }
    }

    /// Update this hasher with more input bytes
    fn update(data: &[u8]) unsafe {
        do vec::as_imm_buf(data) |pdata, len| {
    pub fn update(&self, data: &[u8]) {
        do 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
     */
    fn final() -> ~[u8] unsafe {
    pub fn final(&self) -> ~[u8] {
        let mut res = vec::from_elem(self.len, 0u8);
        do vec::as_mut_buf(res) |pres, _len| {
        do res.as_mut_buf |pres, _len| {
            unsafe {
                libcrypto::EVP_DigestFinal(self.ctx, pres, ptr::null());
            }
        }
        res
    }
}
@@ -87,7 +100,7 @@ pub impl Hasher {
 * 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] {
    let h = Hasher(t);
    h.update(data);
    h.final()
@@ -95,6 +108,8 @@ pub fn hash(t: HashType, data: &[u8]) -> ~[u8] unsafe {

#[cfg(test)]
mod tests {
    use super::*;

    // Test vectors from http://www.nsrl.nist.gov/testdata/
    #[test]
    fn test_md5() {
@@ -102,7 +117,7 @@ mod tests {
        let d0 = 
           ~[0x90u8, 0x01u8, 0x50u8, 0x98u8, 0x3cu8, 0xd2u8, 0x4fu8, 0xb0u8,
             0xd6u8, 0x96u8, 0x3fu8, 0x7du8, 0x28u8, 0xe1u8, 0x7fu8, 0x72u8];
        assert(hash(MD5, s0) == d0);
        assert!(hash(MD5, s0) == d0);
    }

    #[test]
@@ -112,7 +127,7 @@ mod tests {
           ~[0xa9u8, 0x99u8, 0x3eu8, 0x36u8, 0x47u8, 0x06u8, 0x81u8, 0x6au8,
             0xbau8, 0x3eu8, 0x25u8, 0x71u8, 0x78u8, 0x50u8, 0xc2u8, 0x6cu8,
             0x9cu8, 0xd0u8, 0xd8u8, 0x9du8];
        assert(hash(SHA1, s0) == d0);
        assert!(hash(SHA1, s0) == d0);
    }

    #[test]
@@ -123,6 +138,6 @@ mod tests {
             0x41u8, 0x41u8, 0x40u8, 0xdeu8, 0x5du8, 0xaeu8, 0x22u8, 0x23u8,
             0xb0u8, 0x03u8, 0x61u8, 0xa3u8, 0x96u8, 0x17u8, 0x7au8, 0x9cu8,
             0xb4u8, 0x10u8, 0xffu8, 0x61u8, 0xf2u8, 0x00u8, 0x15u8, 0xadu8];
        assert(hash(SHA256, s0) == d0);
        assert!(hash(SHA256, s0) == d0);
    }
}
+106 −80
Original line number Diff line number Diff line
use libc::{c_char, c_uchar, c_int};
use std::libc::c_int;
use std::vec;

#[link_name = "crypto"]
#[abi = "cdecl"]
extern mod libcrypto {
mod libcrypto {
    use std::libc::c_int;

    #[link_args = "-lcrypto"]
    extern {
        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;
    }
}

#[doc = "
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| {
    do pass.as_imm_buf |pass_buf, pass_len| {
        do salt.as_imm_buf |salt_buf, salt_len| {
            let mut out = vec::with_capacity(keylen);

            do vec::as_mut_buf(out) |out_buf, _out_len| {
                let r = libcrypto::PKCS5_PBKDF2_HMAC_SHA1(
            do 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);
                        out_buf)
                };

                if r != 1 as c_int { fail; }
                if r != 1 as c_int { fail!(); }
            }

            unsafe { vec::raw::set_len(&mut out, keylen); }
@@ -40,75 +46,95 @@ 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_eq!(
            pbkdf2_hmac_sha1(
                "password",
            str::to_bytes("salt"),
                "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 pbkdf2_hmac_sha1(
        assert_eq!(
            pbkdf2_hmac_sha1(
                "password",
            str::to_bytes("salt"),
                "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 pbkdf2_hmac_sha1(
        assert_eq!(
            pbkdf2_hmac_sha1(
                "password",
            str::to_bytes("salt"),
                "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 pbkdf2_hmac_sha1(
        assert_eq!(
            pbkdf2_hmac_sha1(
                "password",
            str::to_bytes("salt"),
                "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 pbkdf2_hmac_sha1(
        assert_eq!(
            pbkdf2_hmac_sha1(
                "passwordPASSWORDpassword",
            str::to_bytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"),
                "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 pbkdf2_hmac_sha1(
        assert_eq!(
            pbkdf2_hmac_sha1(
                "pass\x00word",
            str::to_bytes("sa\x00lt"),
                "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
        ];
            ]
        );
    }
}
+228 −195
Original line number Diff line number Diff line
use libc::{c_int, c_uint};
use std::cast;
use std::libc::{c_int, c_uint};
use std::libc;
use std::ptr;
use std::vec;

#[allow(non_camel_case_types)]
type EVP_PKEY = *libc::c_void;
pub type EVP_PKEY = *libc::c_void;

#[allow(non_camel_case_types)]
type ANYKEY = *libc::c_void;
pub type ANYKEY = *libc::c_void;

#[allow(non_camel_case_types)]
type RSA = *libc::c_void;
pub type RSA = *libc::c_void;

#[link_name = "crypto"]
#[abi = "cdecl"]
extern mod libcrypto {
mod libcrypto {
    use super::*;
    use std::libc::{c_int, c_uint};

    #[link_args = "-lcrypto"]
    extern "C" {
        fn EVP_PKEY_new() -> *EVP_PKEY;
        fn EVP_PKEY_free(k: *EVP_PKEY);
    fn EVP_PKEY_assign(k: *EVP_PKEY, t: c_int, inner: *ANYKEY);
        fn EVP_PKEY_assign(k: *EVP_PKEY, t: c_int, inner: *ANYKEY) -> c_int;
        fn EVP_PKEY_get1_RSA(k: *EVP_PKEY) -> *RSA;

    fn i2d_PublicKey(k: *EVP_PKEY, buf: &*mut u8) -> c_int;
    fn d2i_PublicKey(t: c_int, k: &*EVP_PKEY, buf: &*u8, len: c_uint) -> *EVP_PKEY;
    fn i2d_PrivateKey(k: *EVP_PKEY, buf: &*mut u8) -> c_int;
    fn d2i_PrivateKey(t: c_int, k: &*EVP_PKEY, buf: &*u8, len: c_uint) -> *EVP_PKEY;
        fn i2d_PublicKey(k: *EVP_PKEY, buf: **mut u8) -> c_int;
        fn d2i_PublicKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY;
        fn i2d_PrivateKey(k: *EVP_PKEY, buf: **mut u8) -> c_int;
        fn d2i_PrivateKey(t: c_int, k: **EVP_PKEY, buf: **u8, len: c_uint) -> *EVP_PKEY;

        fn RSA_generate_key(modsz: c_uint, e: c_uint, cb: *u8, cbarg: *u8) -> *RSA;
        fn RSA_size(k: *RSA) -> c_uint;
@@ -29,11 +36,12 @@ extern mod libcrypto {
                              pad: c_int) -> c_int;
        fn RSA_private_decrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA,
                               pad: c_int) -> c_int;
    fn RSA_sign(t: c_int, m: *u8, mlen: c_uint, sig: *mut u8, siglen: *c_uint,
        fn RSA_sign(t: c_int, m: *u8, mlen: c_uint, sig: *mut u8, siglen: *mut c_uint,
                    k: *RSA) -> c_int;
        fn RSA_verify(t: c_int, m: *u8, mlen: c_uint, sig: *u8, siglen: c_uint,
                      k: *RSA) -> c_int;
    }
}

enum Parts {
    Neither,
@@ -49,52 +57,59 @@ pub enum Role {
    Verify
}

fn rsa_to_any(rsa: *RSA) -> *ANYKEY unsafe {
    cast::reinterpret_cast(&rsa)
fn rsa_to_any(rsa: *RSA) -> *ANYKEY {
    unsafe {
        cast::transmute(rsa)
    }
}

fn any_to_rsa(anykey: *ANYKEY) -> *RSA unsafe {
    cast::reinterpret_cast(&anykey)
fn any_to_rsa(anykey: *ANYKEY) -> *RSA {
    unsafe {
        cast::transmute(anykey)
    }
}

pub struct PKey {
    priv mut evp: *EVP_PKEY,
    priv mut parts: Parts,
    priv evp: *EVP_PKEY,
    priv parts: Parts,
}

pub fn PKey() -> PKey {
    PKey { evp: libcrypto::EVP_PKEY_new(), parts: Neither }
    PKey {
        evp: unsafe { libcrypto::EVP_PKEY_new() },
        parts: Neither
    }
}

priv impl PKey {
    fn _tostr(f: fn@(*EVP_PKEY, &*mut u8) -> c_int) -> ~[u8] unsafe {
        let buf = ptr::mut_null();
        let len = f(self.evp, &buf);
///Represents a public key, optionally with a private key attached.
impl PKey {
    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 = do vec::as_mut_buf(s) |ps, _len| {
            f(self.evp, &ps)
            let r = do s.as_mut_buf |buf, _| {
                f(self.evp, &buf)
            };

        vec::slice(s, 0u, r as uint)
            s.truncate(r as uint);
            s
        }
    }

    fn _fromstr(
        s: &[u8],
        f: fn@(c_int, &*EVP_PKEY, &*u8, c_uint) -> *EVP_PKEY
    ) unsafe {
        do vec::as_imm_buf(s) |ps, len| {
    fn _fromstr(&mut self, s: &[u8], f: extern "C" unsafe fn(c_int, **EVP_PKEY, **u8, c_uint) -> *EVP_PKEY) {
        do s.as_imm_buf |ps, len| {
            let evp = ptr::null();
            unsafe {
                f(6 as c_int, &evp, &ps, len as c_uint);
            self.evp = evp;
            }
            self.evp = evp;
        }
    }

///Represents a public key, optionally with a private key attached.
pub impl PKey {
    fn gen(keysz: uint) unsafe {
    pub fn gen(&mut self, keysz: uint) {
        unsafe {
            let rsa = libcrypto::RSA_generate_key(
                keysz as c_uint,
                65537u as c_uint,
@@ -107,18 +122,19 @@ 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] {
    pub fn save_pub(&self) -> ~[u8] {
        self._tostr(libcrypto::i2d_PublicKey)
    }

    /**
     * Loads a serialized form of the public key, as produced by save_pub().
     */
    fn load_pub(s: &[u8]) {
    pub fn load_pub(&mut self, s: &[u8]) {
        self._fromstr(s, libcrypto::d2i_PublicKey);
        self.parts = Public;
    }
@@ -127,14 +143,14 @@ pub impl PKey {
     * Returns a serialized form of the public and private keys, suitable for
     * load_priv().
     */
    fn save_priv() -> ~[u8] {
    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().
     */
    fn load_priv(s: &[u8]) {
    pub fn load_priv(&mut self, s: &[u8]) {
        self._fromstr(s, libcrypto::d2i_PrivateKey);
        self.parts = Both;
    }
@@ -142,14 +158,16 @@ pub impl PKey {
    /**
     * Returns the size of the public key modulus.
     */
    fn size() -> uint {
    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.
     */
    fn can(r: Role) -> bool {
    pub fn can(&self, r: Role) -> bool {
        match r {
            Encrypt =>
                match self.parts {
@@ -178,42 +196,47 @@ pub impl PKey {
     * Returns the maximum amount of data that can be encrypted by an encrypt()
     * call.
     */
    fn max_data() -> uint unsafe {
    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
        }
    }

    /**
     * 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 {
    pub fn encrypt(&self, s: &[u8]) -> ~[u8] {
        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
        assert s.len() < libcrypto::RSA_size(rsa) as uint - 41u;
            assert!(s.len() < libcrypto::RSA_size(rsa) as uint - 41u);

            let mut r = vec::from_elem(len as uint + 1u, 0u8);

        do vec::as_mut_buf(r) |pr, _len| {
            do vec::as_imm_buf(s) |ps, s_len| {
            let rv = do r.as_mut_buf |pr, _len| {
                do s.as_imm_buf |ps, s_len| {
                    // XXX: 4 == RSA_PKCS1_OAEP_PADDING
                let rv = libcrypto::RSA_public_encrypt(
                    libcrypto::RSA_public_encrypt(
                        s_len as c_uint,
                        ps,
                        pr,
                        rsa, 4 as c_int
                );
                    )
                }
            };

            if rv < 0 as c_int {
                ~[]
            } else {
                    vec::slice(r, 0u, rv as uint)
                }
                r.truncate(rv as uint);
                r
            }
        }
    }
@@ -221,30 +244,33 @@ pub impl PKey {
    /**
     * Decrypts data, expecting OAEP padding, returning the decrypted data.
     */
    fn decrypt(s: &[u8]) -> ~[u8] unsafe {
    pub fn decrypt(&self, s: &[u8]) -> ~[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);

        do vec::as_mut_buf(r) |pr, _len| {
            do vec::as_imm_buf(s) |ps, s_len| {
            let rv = do r.as_mut_buf |pr, _len| {
                do s.as_imm_buf |ps, s_len| {
                    // XXX: 4 == RSA_PKCS1_OAEP_PADDING
                let rv = libcrypto::RSA_private_decrypt(
                    libcrypto::RSA_private_decrypt(
                        s_len as c_uint,
                        ps,
                        pr,
                        rsa,
                        4 as c_int
                );
                    )
                }
            };

            if rv < 0 as c_int {
                ~[]
            } else {
                    vec::slice(r, 0u, rv as uint)
                }
                r.truncate(rv as uint);
                r
            }
        }
    }
@@ -253,29 +279,32 @@ pub impl PKey {
     * 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 {
    pub fn sign(&self, s: &[u8]) -> ~[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);

        do vec::as_mut_buf(r) |pr, _len| {
            do vec::as_imm_buf(s) |ps, s_len| {
                let plen = ptr::addr_of(&len);
            let rv = do r.as_mut_buf |pr, _len| {
                do s.as_imm_buf |ps, s_len| {
                    let mut len = len;

                    // XXX: 672 == NID_sha256
                let rv = libcrypto::RSA_sign(
                    libcrypto::RSA_sign(
                        672 as c_int,
                        ps,
                        s_len as c_uint,
                        pr,
                    plen,
                    rsa);
                        &mut len,
                        rsa)
                }
            };

            if rv < 0 as c_int {
                ~[]
            } else {
                    vec::slice(r, 0u, *plen as uint)
                }
                r.truncate(len as uint);
                r
            }
        }
    }
@@ -284,11 +313,12 @@ pub impl PKey {
     * 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 {
    pub fn verify(&self, m: &[u8], s: &[u8]) -> bool {
        unsafe {
            let rsa = libcrypto::EVP_PKEY_get1_RSA(self.evp);

        do vec::as_imm_buf(m) |pm, m_len| {
            do vec::as_imm_buf(s) |ps, s_len| {
            do m.as_imm_buf |pm, m_len| {
                do s.as_imm_buf |ps, s_len| {
                    // XXX: 672 == NID_sha256
                    let rv = libcrypto::RSA_verify(
                        672 as c_int,
@@ -304,66 +334,69 @@ pub impl PKey {
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[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_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);
    }
}
+14 −8
Original line number Diff line number Diff line
use libc::{c_uchar, c_int};
use std::libc::c_int;
use std::vec;

#[link_name = "crypto"]
#[abi = "cdecl"]
extern mod libcrypto {
mod libcrypto {
    use std::libc::c_int;

    #[link_args = "-lcrypto"]
    extern {
        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);

    do vec::as_mut_buf(out) |out_buf, len| {
        let r = libcrypto::RAND_bytes(out_buf, len as c_int);
        if r != 1 as c_int { fail }
    do 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 { vec::raw::set_len(&mut out, len); }
@@ -21,6 +25,8 @@ pub fn rand_bytes(len: uint) -> ~[u8] {

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rand_bytes() {
        let _bytes = rand_bytes(5u);
Loading