15
|
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis |
|
2 * |
|
3 * LibTomCrypt is a library that provides various cryptographic |
|
4 * algorithms in a highly modular and flexible manner. |
|
5 * |
|
6 * The library is free for all purposes without any express |
|
7 * guarantee it works. |
|
8 * |
|
9 * Tom St Denis, [email protected], http://libtomcrypt.org |
|
10 */ |
|
11 |
|
12 #include "mycrypt.h" |
|
13 |
|
14 #ifdef MRSA |
|
15 |
143
|
16 /* import an RSAPublicKey or RSAPrivateKey [two-prime only, defined in PKCS #1 v2.1] */ |
15
|
17 int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key) |
|
18 { |
143
|
19 unsigned long x; |
15
|
20 int err; |
|
21 |
|
22 _ARGCHK(in != NULL); |
|
23 _ARGCHK(key != NULL); |
|
24 |
|
25 /* init key */ |
|
26 if ((err = mp_init_multi(&key->e, &key->d, &key->N, &key->dQ, &key->dP, &key->qP, |
143
|
27 &key->p, &key->q, NULL)) != MP_OKAY) { |
15
|
28 return mpi_to_ltc_error(err); |
|
29 } |
|
30 |
143
|
31 /* read first number, it's either N or 0 [0 == private key] */ |
|
32 x = inlen; |
|
33 if ((err = der_get_multi_integer(in, &x, &key->N, NULL)) != CRYPT_OK) { |
|
34 goto __ERR; |
15
|
35 } |
|
36 |
143
|
37 /* advance */ |
|
38 inlen -= x; |
|
39 in += x; |
|
40 |
|
41 if (mp_cmp_d(&key->N, 0) == MP_EQ) { |
|
42 /* it's a private key */ |
|
43 if ((err = der_get_multi_integer(in, &inlen, &key->N, &key->e, |
|
44 &key->d, &key->p, &key->q, &key->dP, |
|
45 &key->dQ, &key->qP, NULL)) != CRYPT_OK) { |
|
46 goto __ERR; |
|
47 } |
15
|
48 |
143
|
49 key->type = PK_PRIVATE; |
|
50 } else { |
|
51 /* it's a public key and we lack e */ |
|
52 if ((err = der_get_multi_integer(in, &inlen, &key->e, NULL)) != CRYPT_OK) { |
|
53 goto __ERR; |
|
54 } |
|
55 |
|
56 /* free up some ram */ |
|
57 mp_clear_multi(&key->p, &key->q, &key->qP, &key->dP, &key->dQ, NULL); |
|
58 |
|
59 key->type = PK_PUBLIC; |
15
|
60 } |
|
61 return CRYPT_OK; |
143
|
62 __ERR: |
15
|
63 mp_clear_multi(&key->d, &key->e, &key->N, &key->dQ, &key->dP, |
143
|
64 &key->qP, &key->p, &key->q, NULL); |
15
|
65 return err; |
|
66 } |
|
67 |
|
68 #endif /* MRSA */ |
|
69 |