2 * Copyright 2002-2018 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
5 * Licensed under the OpenSSL license (the "License"). You may not use
6 * this file except in compliance with the License. You can obtain a copy
7 * in the file LICENSE in the source distribution or at
8 * https://www.openssl.org/source/license.html
14 #include "internal/cryptlib.h"
16 #include <openssl/err.h>
17 #include <openssl/bn.h>
18 #include <openssl/objects.h>
19 #include <openssl/ec.h>
22 int ossl_ecdh_compute_key(unsigned char **psec, size_t *pseclen,
23 const EC_POINT *pub_key, const EC_KEY *ecdh)
25 if (ecdh->group->meth->ecdh_compute_key == NULL) {
26 ECerr(EC_F_OSSL_ECDH_COMPUTE_KEY, EC_R_CURVE_DOES_NOT_SUPPORT_ECDH);
30 return ecdh->group->meth->ecdh_compute_key(psec, pseclen, pub_key, ecdh);
34 * This implementation is based on the following primitives in the IEEE 1363 standard:
38 int ecdh_simple_compute_key(unsigned char **pout, size_t *poutlen,
39 const EC_POINT *pub_key, const EC_KEY *ecdh)
44 const BIGNUM *priv_key;
45 const EC_GROUP *group;
48 unsigned char *buf = NULL;
50 if ((ctx = BN_CTX_new()) == NULL)
55 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
59 priv_key = EC_KEY_get0_private_key(ecdh);
60 if (priv_key == NULL) {
61 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, EC_R_NO_PRIVATE_VALUE);
65 group = EC_KEY_get0_group(ecdh);
67 if (EC_KEY_get_flags(ecdh) & EC_FLAG_COFACTOR_ECDH) {
68 if (!EC_GROUP_get_cofactor(group, x, NULL) ||
69 !BN_mul(x, x, priv_key, ctx)) {
70 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
76 if ((tmp = EC_POINT_new(group)) == NULL) {
77 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
81 if (!EC_POINT_mul(group, tmp, NULL, pub_key, priv_key, ctx)) {
82 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, EC_R_POINT_ARITHMETIC_FAILURE);
86 if (!EC_POINT_get_affine_coordinates(group, tmp, x, NULL, ctx)) {
87 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, EC_R_POINT_ARITHMETIC_FAILURE);
91 buflen = (EC_GROUP_get_degree(group) + 7) / 8;
92 len = BN_num_bytes(x);
94 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, ERR_R_INTERNAL_ERROR);
97 if ((buf = OPENSSL_malloc(buflen)) == NULL) {
98 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, ERR_R_MALLOC_FAILURE);
102 memset(buf, 0, buflen - len);
103 if (len != (size_t)BN_bn2bin(x, buf + buflen - len)) {
104 ECerr(EC_F_ECDH_SIMPLE_COMPUTE_KEY, ERR_R_BN_LIB);
115 EC_POINT_clear_free(tmp);