xref: /optee_os/core/lib/libtomcrypt/src/pk/dh/dh_export.c (revision 8411e6ad673d20c4742ed30c785e3f5cdea54dfa)
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 #ifdef LTC_MDH
7 
8 /**
9   Export a DH key to a binary packet
10   @param out    [out] The destination for the key
11   @param outlen [in/out] The max size and resulting size of the DH key
12   @param type   Which type of key (PK_PRIVATE or PK_PUBLIC)
13   @param key    The key you wish to export
14   @return CRYPT_OK if successful
15 */
dh_export(unsigned char * out,unsigned long * outlen,int type,const dh_key * key)16 int dh_export(unsigned char *out, unsigned long *outlen, int type, const dh_key *key)
17 {
18    unsigned char flags[1];
19    int err;
20    unsigned long version = 0;
21 
22    LTC_ARGCHK(out    != NULL);
23    LTC_ARGCHK(outlen != NULL);
24    LTC_ARGCHK(key    != NULL);
25 
26    if (type == PK_PRIVATE) {
27       /* export x - private key */
28       flags[0] = 1;
29       err = der_encode_sequence_multi(out, outlen,
30                                 LTC_ASN1_SHORT_INTEGER, 1UL, &version,
31                                 LTC_ASN1_BIT_STRING,    1UL, flags,
32                                 LTC_ASN1_INTEGER,       1UL, key->prime,
33                                 LTC_ASN1_INTEGER,       1UL, key->base,
34                                 LTC_ASN1_INTEGER,       1UL, key->x,
35                                 LTC_ASN1_EOL,           0UL, NULL);
36    }
37    else {
38       /* export y - public key */
39       flags[0] = 0;
40       err = der_encode_sequence_multi(out, outlen,
41                                 LTC_ASN1_SHORT_INTEGER, 1UL, &version,
42                                 LTC_ASN1_BIT_STRING,    1UL, flags,
43                                 LTC_ASN1_INTEGER,       1UL, key->prime,
44                                 LTC_ASN1_INTEGER,       1UL, key->base,
45                                 LTC_ASN1_INTEGER,       1UL, key->y,
46                                 LTC_ASN1_EOL,           0UL, NULL);
47    }
48 
49    return err;
50 }
51 
52 #endif /* LTC_MDH */
53