1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4
5 /**
6 @file rsa_export.c
7 Export RSA PKCS keys, Tom St Denis
8 */
9
10 #ifdef LTC_MRSA
11
12 /**
13 This will export either an RSAPublicKey or RSAPrivateKey [defined in PKCS #1 v2.1]
14 @param out [out] Destination of the packet
15 @param outlen [in/out] The max size and resulting size of the packet
16 @param type The type of exported key (PK_PRIVATE or PK_PUBLIC)
17 @param key The RSA key to export
18 @return CRYPT_OK if successful
19 */
rsa_export(unsigned char * out,unsigned long * outlen,int type,const rsa_key * key)20 int rsa_export(unsigned char *out, unsigned long *outlen, int type, const rsa_key *key)
21 {
22 unsigned long zero=0;
23 int err, std;
24 LTC_ARGCHK(out != NULL);
25 LTC_ARGCHK(outlen != NULL);
26 LTC_ARGCHK(key != NULL);
27
28 std = type & PK_STD;
29 type &= ~PK_STD;
30
31 if (type == PK_PRIVATE && key->type != PK_PRIVATE) {
32 return CRYPT_PK_TYPE_MISMATCH;
33 }
34
35 if (type == PK_PRIVATE) {
36 /* private key */
37 /* output is
38 Version, n, e, d, p, q, d mod (p-1), d mod (q - 1), 1/q mod p
39 */
40 return der_encode_sequence_multi(out, outlen,
41 LTC_ASN1_SHORT_INTEGER, 1UL, &zero,
42 LTC_ASN1_INTEGER, 1UL, key->N,
43 LTC_ASN1_INTEGER, 1UL, key->e,
44 LTC_ASN1_INTEGER, 1UL, key->d,
45 LTC_ASN1_INTEGER, 1UL, key->p,
46 LTC_ASN1_INTEGER, 1UL, key->q,
47 LTC_ASN1_INTEGER, 1UL, key->dP,
48 LTC_ASN1_INTEGER, 1UL, key->dQ,
49 LTC_ASN1_INTEGER, 1UL, key->qP,
50 LTC_ASN1_EOL, 0UL, NULL);
51 }
52
53 if (type == PK_PUBLIC) {
54 /* public key */
55 unsigned long tmplen, *ptmplen;
56 unsigned char* tmp = NULL;
57
58 if (std) {
59 tmplen = (unsigned long)(mp_count_bits(key->N) / 8) * 2 + 8;
60 tmp = XMALLOC(tmplen);
61 ptmplen = &tmplen;
62 if (tmp == NULL) {
63 return CRYPT_MEM;
64 }
65 }
66 else {
67 tmp = out;
68 ptmplen = outlen;
69 }
70
71 err = der_encode_sequence_multi(tmp, ptmplen,
72 LTC_ASN1_INTEGER, 1UL, key->N,
73 LTC_ASN1_INTEGER, 1UL, key->e,
74 LTC_ASN1_EOL, 0UL, NULL);
75
76 if ((err != CRYPT_OK) || !std) {
77 goto finish;
78 }
79
80 err = x509_encode_subject_public_key_info(out, outlen,
81 LTC_OID_RSA, tmp, tmplen, LTC_ASN1_NULL, NULL, 0);
82
83 finish:
84 if (tmp != out) XFREE(tmp);
85 return err;
86 }
87
88 return CRYPT_INVALID_ARG;
89 }
90
91 #endif /* LTC_MRSA */
92