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