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_MDH
14 
15 /**
16   Export a DH key to a binary packet
17   @param out    [out] The destination for the key
18   @param outlen [in/out] The max size and resulting size of the DH key
19   @param type   Which type of key (PK_PRIVATE or PK_PUBLIC)
20   @param key    The key you wish to export
21   @return CRYPT_OK if successful
22 */
dh_export(unsigned char * out,unsigned long * outlen,int type,const dh_key * key)23 int dh_export(unsigned char *out, unsigned long *outlen, int type, const dh_key *key)
24 {
25    unsigned char flags[1];
26    int err;
27    unsigned long version = 0;
28 
29    LTC_ARGCHK(out    != NULL);
30    LTC_ARGCHK(outlen != NULL);
31    LTC_ARGCHK(key    != NULL);
32 
33    if (type == PK_PRIVATE) {
34       /* export x - private key */
35       flags[0] = 1;
36       err = der_encode_sequence_multi(out, outlen,
37                                 LTC_ASN1_SHORT_INTEGER, 1UL, &version,
38                                 LTC_ASN1_BIT_STRING,    1UL, flags,
39                                 LTC_ASN1_INTEGER,       1UL, key->prime,
40                                 LTC_ASN1_INTEGER,       1UL, key->base,
41                                 LTC_ASN1_INTEGER,       1UL, key->x,
42                                 LTC_ASN1_EOL,           0UL, NULL);
43    }
44    else {
45       /* export y - public key */
46       flags[0] = 0;
47       err = der_encode_sequence_multi(out, outlen,
48                                 LTC_ASN1_SHORT_INTEGER, 1UL, &version,
49                                 LTC_ASN1_BIT_STRING,    1UL, flags,
50                                 LTC_ASN1_INTEGER,       1UL, key->prime,
51                                 LTC_ASN1_INTEGER,       1UL, key->base,
52                                 LTC_ASN1_INTEGER,       1UL, key->y,
53                                 LTC_ASN1_EOL,           0UL, NULL);
54    }
55 
56    return err;
57 }
58 
59 #endif /* LTC_MDH */
60 
61 /* ref:         $Format:%D$ */
62 /* git commit:  $Format:%H$ */
63 /* commit time: $Format:%ai$ */
64