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 
11 #include "tomcrypt_private.h"
12 
13 /**
14   @file ecc_export.c
15   ECC Crypto, Tom St Denis
16 */
17 
18 #ifdef LTC_MECC
19 
20 /**
21   Export an ECC key as a binary packet
22   @param out     [out] Destination for the key
23   @param outlen  [in/out] Max size and resulting size of the exported key
24   @param type    The type of key you want to export (PK_PRIVATE or PK_PUBLIC)
25   @param key     The key to export
26   @return CRYPT_OK if successful
27 */
ecc_export(unsigned char * out,unsigned long * outlen,int type,const ecc_key * key)28 int ecc_export(unsigned char *out, unsigned long *outlen, int type, const ecc_key *key)
29 {
30    int           err;
31    unsigned char flags[1];
32    unsigned long key_size;
33 
34    LTC_ARGCHK(out    != NULL);
35    LTC_ARGCHK(outlen != NULL);
36    LTC_ARGCHK(key    != NULL);
37 
38    /* type valid? */
39    if (key->type != PK_PRIVATE && type == PK_PRIVATE) {
40       return CRYPT_PK_TYPE_MISMATCH;
41    }
42 
43    /* we store the NIST byte size */
44    key_size = key->dp.size;
45 
46    if (type == PK_PRIVATE) {
47        flags[0] = 1;
48        err = der_encode_sequence_multi(out, outlen,
49                                  LTC_ASN1_BIT_STRING,      1UL, flags,
50                                  LTC_ASN1_SHORT_INTEGER,   1UL, &key_size,
51                                  LTC_ASN1_INTEGER,         1UL, key->pubkey.x,
52                                  LTC_ASN1_INTEGER,         1UL, key->pubkey.y,
53                                  LTC_ASN1_INTEGER,         1UL, key->k,
54                                  LTC_ASN1_EOL,             0UL, NULL);
55    } else {
56        flags[0] = 0;
57        err = der_encode_sequence_multi(out, outlen,
58                                  LTC_ASN1_BIT_STRING,      1UL, flags,
59                                  LTC_ASN1_SHORT_INTEGER,   1UL, &key_size,
60                                  LTC_ASN1_INTEGER,         1UL, key->pubkey.x,
61                                  LTC_ASN1_INTEGER,         1UL, key->pubkey.y,
62                                  LTC_ASN1_EOL,             0UL, NULL);
63    }
64 
65    return err;
66 }
67 
68 #endif
69 /* ref:         $Format:%D$ */
70 /* git commit:  $Format:%H$ */
71 /* commit time: $Format:%ai$ */
72 
73