1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3
4 #include "tomcrypt_private.h"
5
6 /**
7 @file ecc_shared_secret.c
8 ECC Crypto, Tom St Denis
9 */
10
11 #ifdef LTC_MECC
12
13 /**
14 Create an ECC shared secret between two keys
15 @param private_key The private ECC key
16 @param public_key The public key
17 @param out [out] Destination of the shared secret (Conforms to EC-DH from ANSI X9.63)
18 @param outlen [in/out] The max size and resulting size of the shared secret
19 @return CRYPT_OK if successful
20 */
ecc_shared_secret(const ecc_key * private_key,const ecc_key * public_key,unsigned char * out,unsigned long * outlen)21 int ecc_shared_secret(const ecc_key *private_key, const ecc_key *public_key,
22 unsigned char *out, unsigned long *outlen)
23 {
24 unsigned long x;
25 ecc_point *result;
26 void *prime, *a;
27 int err;
28
29 LTC_ARGCHK(private_key != NULL);
30 LTC_ARGCHK(public_key != NULL);
31 LTC_ARGCHK(out != NULL);
32 LTC_ARGCHK(outlen != NULL);
33
34 /* type valid? */
35 if (private_key->type != PK_PRIVATE) {
36 return CRYPT_PK_NOT_PRIVATE;
37 }
38
39 /* make new point */
40 result = ltc_ecc_new_point();
41 if (result == NULL) {
42 return CRYPT_MEM;
43 }
44
45 prime = private_key->dp.prime;
46 a = private_key->dp.A;
47
48 if ((err = ltc_mp.ecc_ptmul(private_key->k, &public_key->pubkey, result, a, prime, 1)) != CRYPT_OK) { goto done; }
49
50 x = (unsigned long)mp_unsigned_bin_size(prime);
51 if (*outlen < x) {
52 *outlen = x;
53 err = CRYPT_BUFFER_OVERFLOW;
54 goto done;
55 }
56 zeromem(out, x);
57 if ((err = mp_to_unsigned_bin(result->x, out + (x - mp_unsigned_bin_size(result->x)))) != CRYPT_OK) { goto done; }
58
59 err = CRYPT_OK;
60 *outlen = x;
61 done:
62 ltc_ecc_del_point(result);
63 return err;
64 }
65
66 #endif
67