1 /**********************************************************************
2 * Copyright (c) 2015 Andrew Poelstra *
3 * Distributed under the MIT software license, see the accompanying *
4 * file COPYING or http://www.opensource.org/licenses/mit-license.php.*
5 **********************************************************************/
7 #ifndef _SECP256K1_MODULE_ECDH_MAIN_
8 #define _SECP256K1_MODULE_ECDH_MAIN_
10 #include "ecmult_const_impl.h"
12 int secp256k1_ecdh(const secp256k1_context_t* ctx, unsigned char *result, const secp256k1_pubkey_t *point, const unsigned char *scalar) {
18 ARG_CHECK(result != NULL);
19 ARG_CHECK(point != NULL);
20 ARG_CHECK(scalar != NULL);
23 secp256k1_pubkey_load(ctx, &pt, point);
24 secp256k1_scalar_set_b32(&s, scalar, &overflow);
25 if (overflow || secp256k1_scalar_is_zero(&s)) {
30 secp256k1_sha256_t sha;
32 secp256k1_ecmult_const(&res, &pt, &s);
33 secp256k1_ge_set_gej(&pt, &res);
34 /* Compute a hash of the point in compressed form
35 * Note we cannot use secp256k1_eckey_pubkey_serialize here since it does not
36 * expect its output to be secret and has a timing sidechannel. */
37 secp256k1_fe_normalize(&pt.x);
38 secp256k1_fe_normalize(&pt.y);
39 secp256k1_fe_get_b32(x, &pt.x);
40 y[0] = 0x02 | secp256k1_fe_is_odd(&pt.y);
42 secp256k1_sha256_initialize(&sha);
43 secp256k1_sha256_write(&sha, y, sizeof(y));
44 secp256k1_sha256_write(&sha, x, sizeof(x));
45 secp256k1_sha256_finalize(&sha, result);
49 secp256k1_scalar_clear(&s);