1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 /**
7   @file ecc_export.c
8   ECC Crypto, Tom St Denis
9 */
10 
11 #ifdef LTC_MECC
12 
13 /**
14   Export an ECC key as a binary packet
15   @param out     [out] Destination for the key
16   @param outlen  [in/out] Max size and resulting size of the exported key
17   @param type    The type of key you want to export (PK_PRIVATE or PK_PUBLIC)
18   @param key     The key to export
19   @return CRYPT_OK if successful
20 */
ecc_export(unsigned char * out,unsigned long * outlen,int type,const ecc_key * key)21 int ecc_export(unsigned char *out, unsigned long *outlen, int type, const ecc_key *key)
22 {
23    int           err;
24    unsigned char flags[1];
25    unsigned long key_size;
26 
27    LTC_ARGCHK(out    != NULL);
28    LTC_ARGCHK(outlen != NULL);
29    LTC_ARGCHK(key    != NULL);
30 
31    /* type valid? */
32    if (key->type != PK_PRIVATE && type == PK_PRIVATE) {
33       return CRYPT_PK_TYPE_MISMATCH;
34    }
35 
36    /* we store the NIST byte size */
37    key_size = key->dp.size;
38 
39    if (type == PK_PRIVATE) {
40        flags[0] = 1;
41        err = der_encode_sequence_multi(out, outlen,
42                                  LTC_ASN1_BIT_STRING,      1UL, flags,
43                                  LTC_ASN1_SHORT_INTEGER,   1UL, &key_size,
44                                  LTC_ASN1_INTEGER,         1UL, key->pubkey.x,
45                                  LTC_ASN1_INTEGER,         1UL, key->pubkey.y,
46                                  LTC_ASN1_INTEGER,         1UL, key->k,
47                                  LTC_ASN1_EOL,             0UL, NULL);
48    } else {
49        flags[0] = 0;
50        err = der_encode_sequence_multi(out, outlen,
51                                  LTC_ASN1_BIT_STRING,      1UL, flags,
52                                  LTC_ASN1_SHORT_INTEGER,   1UL, &key_size,
53                                  LTC_ASN1_INTEGER,         1UL, key->pubkey.x,
54                                  LTC_ASN1_INTEGER,         1UL, key->pubkey.y,
55                                  LTC_ASN1_EOL,             0UL, NULL);
56    }
57 
58    return err;
59 }
60 
61 #endif
62