comparison src/pk/rsa/rsa_export.c @ 191:1c15b283127b libtomcrypt-orig

Import of libtomcrypt 1.02 with manual path rename rearrangement etc
author Matt Johnston <matt@ucc.asn.au>
date Fri, 06 May 2005 13:23:02 +0000
parents
children 39d5d58461d6
comparison
equal deleted inserted replaced
143:5d99163f7e32 191:1c15b283127b
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 #include "tomcrypt.h"
12
13 /**
14 @file rsa_export.c
15 Export RSA PKCS keys, Tom St Denis
16 */
17
18 #ifdef MRSA
19
20 /**
21 This will export either an RSAPublicKey or RSAPrivateKey [defined in PKCS #1 v2.1]
22 @param out [out] Destination of the packet
23 @param outlen [in/out] The max size and resulting size of the packet
24 @param type The type of exported key (PK_PRIVATE or PK_PUBLIC)
25 @param key The RSA key to export
26 @return CRYPT_OK if successful
27 */
28 int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key)
29 {
30 int err, x;
31
32 LTC_ARGCHK(out != NULL);
33 LTC_ARGCHK(outlen != NULL);
34 LTC_ARGCHK(key != NULL);
35
36 /* type valid? */
37 if (!(key->type == PK_PRIVATE) && (type == PK_PRIVATE)) {
38 return CRYPT_PK_INVALID_TYPE;
39 }
40 if (*outlen < 4) {
41 return CRYPT_BUFFER_OVERFLOW;
42 }
43
44 /* Mental Note: push space for the header 0x30 0x82 LL LL (LL = length of packet EXcluding 4 bytes)
45 * we assume LL > 255 which is true since the smallest RSA key has a 128-byte modulus (1024-bit)
46 */
47 *outlen -= 4;
48
49 if (type == PK_PRIVATE) {
50 /* private key */
51 mp_int zero;
52
53 /* first INTEGER == 0 to signify two-prime RSA */
54 if ((err = mp_init(&zero)) != MP_OKAY) {
55 return mpi_to_ltc_error(err);
56 }
57
58 /* output is
59 Version, n, e, d, p, q, d mod (p-1), d mod (q - 1), 1/q mod p
60 */
61 if ((err = der_put_multi_integer(
62 out+4, outlen, &zero, &key->N, &key->e,
63 &key->d, &key->p, &key->q, &key->dP,
64 &key->dQ, &key->qP, NULL)) != CRYPT_OK) {
65 mp_clear(&zero);
66 return err;
67 }
68
69 /* clear zero and return */
70 mp_clear(&zero);
71 } else {
72 /* public key */
73 if ((err = der_put_multi_integer(out+4, outlen, &key->N, &key->e, NULL)) != CRYPT_OK) {
74 return err;
75 }
76 }
77
78 /* store the header */
79 out[0] = 0x30;
80 if (*outlen < 256) {
81 /* shift the output up one byte if the header is only 3 bytes */
82 for (x = 0; x < *outlen; x++) {
83 out[x+3] = out[x+4];
84 }
85 out[1] = 0x81;
86 out[2] = (*outlen & 255);
87 *outlen += 3;
88 } else {
89 out[1] = 0x82;
90 out[2] = (*outlen >> 8) & 255;
91 out[3] = (*outlen & 255);
92 *outlen += 4;
93 }
94 return err;
95 }
96
97 #endif /* MRSA */
98