1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 #ifdef LTC_MECC
7 
8 /** Export raw public or private key (public keys = ANS X9.63 compressed or uncompressed; private keys = raw bytes)
9   @param out    [out] destination of export
10   @param outlen [in/out]  Length of destination and final output size
11   @param type   PK_PRIVATE, PK_PUBLIC or PK_PUBLIC|PK_COMPRESSED
12   @param key    Key to export
13   Return        CRYPT_OK on success
14 */
15 
ecc_get_key(unsigned char * out,unsigned long * outlen,int type,const ecc_key * key)16 int ecc_get_key(unsigned char *out, unsigned long *outlen, int type, const ecc_key *key)
17 {
18    unsigned long size, ksize;
19    int err, compressed;
20 
21    LTC_ARGCHK(key    != NULL);
22    LTC_ARGCHK(out    != NULL);
23    LTC_ARGCHK(outlen != NULL);
24 
25    size = key->dp.size;
26    compressed = type & PK_COMPRESSED ? 1 : 0;
27    type &= ~PK_COMPRESSED;
28 
29    if (type == PK_PUBLIC) {
30       if ((err = ltc_ecc_export_point(out, outlen, key->pubkey.x, key->pubkey.y, size, compressed)) != CRYPT_OK) {
31          return err;
32       }
33    }
34    else if (type == PK_PRIVATE) {
35       if (key->type != PK_PRIVATE)                                                return CRYPT_PK_TYPE_MISMATCH;
36       *outlen = size;
37       if (size > *outlen)                                                         return CRYPT_BUFFER_OVERFLOW;
38       if ((ksize = mp_unsigned_bin_size(key->k)) > size)                          return CRYPT_BUFFER_OVERFLOW;
39       /* pad and store k */
40       if ((err = mp_to_unsigned_bin(key->k, out + (size - ksize))) != CRYPT_OK)   return err;
41       zeromem(out, size - ksize);
42    }
43    else {
44       return CRYPT_INVALID_ARG;
45    }
46 
47    return CRYPT_OK;
48 }
49 
50 #endif
51