1 // Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
2 // Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // https://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15
16 #include <openssl/ecdh.h>
17
18 #include <limits.h>
19 #include <string.h>
20
21 #include <openssl/digest.h>
22 #include <openssl/err.h>
23 #include <openssl/mem.h>
24
25 #include "../fipsmodule/ec/internal.h"
26 #include "../internal.h"
27
28
ECDH_compute_key(void * out,size_t out_len,const EC_POINT * pub_key,const EC_KEY * priv_key,void * (* kdf)(const void * in,size_t inlen,void * out,size_t * out_len))29 int ECDH_compute_key(void *out, size_t out_len, const EC_POINT *pub_key,
30 const EC_KEY *priv_key,
31 void *(*kdf)(const void *in, size_t inlen, void *out,
32 size_t *out_len)) {
33 if (priv_key->priv_key == NULL) {
34 OPENSSL_PUT_ERROR(ECDH, ECDH_R_NO_PRIVATE_VALUE);
35 return -1;
36 }
37 const EC_SCALAR *const priv = &priv_key->priv_key->scalar;
38 const EC_GROUP *const group = EC_KEY_get0_group(priv_key);
39 if (EC_GROUP_cmp(group, pub_key->group, NULL) != 0) {
40 OPENSSL_PUT_ERROR(EC, EC_R_INCOMPATIBLE_OBJECTS);
41 return -1;
42 }
43
44 EC_JACOBIAN shared_point;
45 uint8_t buf[EC_MAX_BYTES];
46 size_t buf_len;
47 if (!ec_point_mul_scalar(group, &shared_point, &pub_key->raw, priv) ||
48 !ec_get_x_coordinate_as_bytes(group, buf, &buf_len, sizeof(buf),
49 &shared_point)) {
50 OPENSSL_PUT_ERROR(ECDH, ECDH_R_POINT_ARITHMETIC_FAILURE);
51 return -1;
52 }
53
54 if (kdf != NULL) {
55 if (kdf(buf, buf_len, out, &out_len) == NULL) {
56 OPENSSL_PUT_ERROR(ECDH, ECDH_R_KDF_FAILED);
57 return -1;
58 }
59 } else {
60 // no KDF, just copy as much as we can
61 if (buf_len < out_len) {
62 out_len = buf_len;
63 }
64 OPENSSL_memcpy(out, buf, out_len);
65 }
66
67 if (out_len > INT_MAX) {
68 OPENSSL_PUT_ERROR(ECDH, ERR_R_OVERFLOW);
69 return -1;
70 }
71
72 return (int)out_len;
73 }
74