aboutsummaryrefslogtreecommitdiff
path: root/pkey.rs
blob: 5fe399b0985a1af400a582b58507499334d77433 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use libc::{c_int, c_uint};

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

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

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

#[link_name = "crypto"]
#[abi = "cdecl"]
extern mod libcrypto {
    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_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 RSA_generate_key(modsz: c_uint, e: c_uint, cb: *u8, cbarg: *u8) -> *RSA;
    fn RSA_size(k: *RSA) -> c_uint;

    fn RSA_public_encrypt(flen: c_uint, from: *u8, to: *mut u8, k: *RSA,
                          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,
                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,
    Public,
    Both
}

#[doc = "Represents a role an asymmetric key might be appropriate for."]
pub enum Role {
    Encrypt,
    Decrypt,
    Sign,
    Verify
}

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

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

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

pub fn PKey() -> PKey {
    PKey { evp: 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);
        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)
        };

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

    fn _fromstr(
        s: &[u8],
        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);
            self.evp = evp;
        }
    }
}

///Represents a public key, optionally with a private key attached.
pub impl PKey {
    fn gen(keysz: uint) unsafe {
        let rsa = libcrypto::RSA_generate_key(
            keysz as c_uint,
            65537u as c_uint,
            ptr::null(),
            ptr::null()
        );

        let rsa_ = rsa_to_any(rsa);
        // XXX: 6 == NID_rsaEncryption
        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] {
        self._tostr(libcrypto::i2d_PublicKey)
    }

    /**
     * Loads a serialized form of the public key, as produced by save_pub().
     */
    fn load_pub(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().
     */
    fn save_priv() -> ~[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]) {
        self._fromstr(s, libcrypto::d2i_PrivateKey);
        self.parts = Both;
    }

    /**
     * Returns the size of the public key modulus.
     */
    fn size() -> uint {
        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 {
        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.
     */
    fn max_data() -> 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 {
        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;

        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| {
                // XXX: 4 == RSA_PKCS1_OAEP_PADDING
                let rv = 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)
                }
            }
        }
    }

    /**
     * Decrypts data, expecting OAEP padding, returning the decrypted data.
     */
    fn decrypt(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);

        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| {
                // XXX: 4 == RSA_PKCS1_OAEP_PADDING
                let rv = 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)
                }
            }
        }
    }

    /**
     * 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 {
        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);

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

                if rv < 0 as c_int {
                    ~[]
                } else {
                    vec::slice(r, 0u, *plen as uint)
                }
            }
        }
    }

    /**
     * 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 {
        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| {
                // XXX: 672 == NID_sha256
                let rv = libcrypto::RSA_verify(
                    672 as c_int,
                    pm,
                    m_len as c_uint,
                    ps,
                    s_len as c_uint,
                    rsa
                );

                rv == 1 as c_int
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_gen_pub() {
        let k0 = PKey();
        let 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));
    }

    #[test]
    fn test_gen_priv() {
        let k0 = PKey();
        let 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));
    }

    #[test]
    fn test_encrypt() {
        let k0 = PKey();
        let 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);
    }

    #[test]
    fn test_sign() {
        let k0 = PKey();
        let 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);
    }
}