1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6   @file rsa_import.c
7   Import an RSA key from a X.509 certificate, Steffen Jaeckel
8 */
9 
10 #ifdef LTC_MRSA
11 
s_rsa_decode(const unsigned char * in,unsigned long inlen,rsa_key * key)12 static int s_rsa_decode(const unsigned char *in, unsigned long inlen, rsa_key *key)
13 {
14    /* now it should be SEQUENCE { INTEGER, INTEGER } */
15    return der_decode_sequence_multi(in, inlen,
16                                         LTC_ASN1_INTEGER, 1UL, key->N,
17                                         LTC_ASN1_INTEGER, 1UL, key->e,
18                                         LTC_ASN1_EOL,     0UL, NULL);
19 }
20 
21 /**
22   Import an RSA key from a X.509 certificate
23   @param in      The packet to import from
24   @param inlen   It's length (octets)
25   @param key     [out] Destination for newly imported key
26   @return CRYPT_OK if successful, upon error allocated memory is freed
27 */
rsa_import_x509(const unsigned char * in,unsigned long inlen,rsa_key * key)28 int rsa_import_x509(const unsigned char *in, unsigned long inlen, rsa_key *key)
29 {
30    int           err;
31 
32    LTC_ARGCHK(in          != NULL);
33    LTC_ARGCHK(key         != NULL);
34    LTC_ARGCHK(ltc_mp.name != NULL);
35 
36    /* init key */
37    if ((err = rsa_init(key)) != CRYPT_OK) {
38       return err;
39    }
40 
41    if ((err = x509_decode_public_key_from_certificate(in, inlen,
42                                                       LTC_OID_RSA, LTC_ASN1_NULL,
43                                                       NULL, NULL,
44                                                       (public_key_decode_cb)s_rsa_decode, key)) != CRYPT_OK) {
45       rsa_free(key);
46    } else {
47       key->type = PK_PUBLIC;
48    }
49 
50    return err;
51 }
52 
53 #endif /* LTC_MRSA */
54 
55