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 #ifdef LTC_MECC
14 
15 /** Export raw public or private key (public keys = ANS X9.63 compressed or uncompressed; private keys = raw bytes)
16   @param out    [out] destination of export
17   @param outlen [in/out]  Length of destination and final output size
18   @param type   PK_PRIVATE, PK_PUBLIC or PK_PUBLIC|PK_COMPRESSED
19   @param key    Key to export
20   Return        CRYPT_OK on success
21 */
22 
ecc_get_key(unsigned char * out,unsigned long * outlen,int type,const ecc_key * key)23 int ecc_get_key(unsigned char *out, unsigned long *outlen, int type, const ecc_key *key)
24 {
25    unsigned long size, ksize;
26    int err, compressed;
27 
28    LTC_ARGCHK(key    != NULL);
29    LTC_ARGCHK(out    != NULL);
30    LTC_ARGCHK(outlen != NULL);
31 
32    size = key->dp.size;
33    compressed = type & PK_COMPRESSED ? 1 : 0;
34    type &= ~PK_COMPRESSED;
35 
36    if (type == PK_PUBLIC) {
37       if ((err = ltc_ecc_export_point(out, outlen, key->pubkey.x, key->pubkey.y, size, compressed)) != CRYPT_OK) {
38          return err;
39       }
40    }
41    else if (type == PK_PRIVATE) {
42       if (key->type != PK_PRIVATE)                                                return CRYPT_PK_TYPE_MISMATCH;
43       *outlen = size;
44       if (size > *outlen)                                                         return CRYPT_BUFFER_OVERFLOW;
45       if ((ksize = mp_unsigned_bin_size(key->k)) > size)                          return CRYPT_BUFFER_OVERFLOW;
46       /* pad and store k */
47       if ((err = mp_to_unsigned_bin(key->k, out + (size - ksize))) != CRYPT_OK)   return err;
48       zeromem(out, size - ksize);
49    }
50    else {
51       return CRYPT_INVALID_ARG;
52    }
53 
54    return CRYPT_OK;
55 }
56 
57 #endif
58 
59 /* ref:         $Format:%D$ */
60 /* git commit:  $Format:%H$ */
61 /* commit time: $Format:%ai$ */
62