Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/crypto/openssl/demos/keyexch/ecdh.c
108307 views
1
/*
2
* Copyright 2023-2024 The OpenSSL Project Authors. All Rights Reserved.
3
*
4
* Licensed under the Apache License 2.0 (the "License"). You may not use
5
* this file except in compliance with the License. You can obtain a copy
6
* in the file LICENSE in the source distribution or at
7
* https://www.openssl.org/source/license.html
8
*/
9
10
#include <stdio.h>
11
#include <string.h>
12
#include <openssl/core_names.h>
13
#include <openssl/evp.h>
14
#include <openssl/err.h>
15
16
/*
17
* This is a demonstration of key exchange using ECDH.
18
*
19
* EC key exchange requires 2 parties (peers) to first agree on shared group
20
* parameters (the EC curve name). Each peer then generates a public/private
21
* key pair using the shared curve name. Each peer then gives their public key
22
* to the other peer. A peer can then derive the same shared secret using their
23
* private key and the other peers public key.
24
*/
25
26
/* Object used to store information for a single Peer */
27
typedef struct peer_data_st {
28
const char *name; /* name of peer */
29
const char *curvename; /* The shared curve name */
30
EVP_PKEY *priv; /* private keypair */
31
EVP_PKEY *pub; /* public key to send to other peer */
32
unsigned char *secret; /* allocated shared secret buffer */
33
size_t secretlen;
34
} PEER_DATA;
35
36
/*
37
* The public key needs to be given to the other peer
38
* The following code extracts the public key data from the private key
39
* and then builds an EVP_KEY public key.
40
*/
41
static int get_peer_public_key(PEER_DATA *peer, OSSL_LIB_CTX *libctx)
42
{
43
int ret = 0;
44
EVP_PKEY_CTX *ctx;
45
OSSL_PARAM params[3];
46
unsigned char pubkeydata[256];
47
size_t pubkeylen;
48
49
/* Get the EC encoded public key data from the peers private key */
50
if (!EVP_PKEY_get_octet_string_param(peer->priv, OSSL_PKEY_PARAM_PUB_KEY,
51
pubkeydata, sizeof(pubkeydata),
52
&pubkeylen))
53
return 0;
54
55
/* Create a EC public key from the public key data */
56
ctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", NULL);
57
if (ctx == NULL)
58
return 0;
59
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
60
(char *)peer->curvename, 0);
61
params[1] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
62
pubkeydata, pubkeylen);
63
params[2] = OSSL_PARAM_construct_end();
64
ret = EVP_PKEY_fromdata_init(ctx) > 0
65
&& (EVP_PKEY_fromdata(ctx, &peer->pub, EVP_PKEY_PUBLIC_KEY,
66
params)
67
> 0);
68
EVP_PKEY_CTX_free(ctx);
69
return ret;
70
}
71
72
static int create_peer(PEER_DATA *peer, OSSL_LIB_CTX *libctx)
73
{
74
int ret = 0;
75
EVP_PKEY_CTX *ctx = NULL;
76
OSSL_PARAM params[2];
77
78
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
79
(char *)peer->curvename, 0);
80
params[1] = OSSL_PARAM_construct_end();
81
82
ctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", NULL);
83
if (ctx == NULL)
84
return 0;
85
86
if (EVP_PKEY_keygen_init(ctx) <= 0
87
|| !EVP_PKEY_CTX_set_params(ctx, params)
88
|| EVP_PKEY_generate(ctx, &peer->priv) <= 0
89
|| !get_peer_public_key(peer, libctx)) {
90
EVP_PKEY_free(peer->priv);
91
peer->priv = NULL;
92
goto err;
93
}
94
ret = 1;
95
err:
96
EVP_PKEY_CTX_free(ctx);
97
return ret;
98
}
99
100
static void destroy_peer(PEER_DATA *peer)
101
{
102
EVP_PKEY_free(peer->priv);
103
EVP_PKEY_free(peer->pub);
104
}
105
106
static int generate_secret(PEER_DATA *peerA, EVP_PKEY *peerBpub,
107
OSSL_LIB_CTX *libctx)
108
{
109
unsigned char *secret = NULL;
110
size_t secretlen = 0;
111
EVP_PKEY_CTX *derivectx;
112
113
/* Create an EVP_PKEY_CTX that contains peerA's private key */
114
derivectx = EVP_PKEY_CTX_new_from_pkey(libctx, peerA->priv, NULL);
115
if (derivectx == NULL)
116
return 0;
117
118
if (EVP_PKEY_derive_init(derivectx) <= 0)
119
goto cleanup;
120
/* Set up peerB's public key */
121
if (EVP_PKEY_derive_set_peer(derivectx, peerBpub) <= 0)
122
goto cleanup;
123
124
/*
125
* For backwards compatibility purposes the OpenSSL ECDH provider supports
126
* optionally using a X963KDF to expand the secret data. This can be done
127
* with code similar to the following.
128
*
129
* OSSL_PARAM params[5];
130
* size_t outlen = 128;
131
* unsigned char ukm[] = { 1, 2, 3, 4 };
132
* params[0] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_TYPE,
133
* "X963KDF", 0);
134
* params[1] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_DIGEST,
135
* "SHA256", 0);
136
* params[2] = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN,
137
* &outlen);
138
* params[3] = OSSL_PARAM_construct_octet_string(OSSL_EXCHANGE_PARAM_KDF_UKM,
139
* ukm, sizeof(ukm));
140
* params[4] = OSSL_PARAM_construct_end();
141
* if (!EVP_PKEY_CTX_set_params(derivectx, params))
142
* goto cleanup;
143
*
144
* Note: After the secret is generated below, the peer could alternatively
145
* pass the secret to a KDF to derive additional key data from the secret.
146
* See demos/kdf/hkdf.c for an example (where ikm is the secret key)
147
*/
148
149
/* Calculate the size of the secret and allocate space */
150
if (EVP_PKEY_derive(derivectx, NULL, &secretlen) <= 0)
151
goto cleanup;
152
secret = (unsigned char *)OPENSSL_malloc(secretlen);
153
if (secret == NULL)
154
goto cleanup;
155
156
/*
157
* Derive the shared secret. In this example 32 bytes are generated.
158
* For EC curves the secret size is related to the degree of the curve
159
* which is 256 bits for P-256.
160
*/
161
if (EVP_PKEY_derive(derivectx, secret, &secretlen) <= 0)
162
goto cleanup;
163
peerA->secret = secret;
164
peerA->secretlen = secretlen;
165
166
printf("Shared secret (%s):\n", peerA->name);
167
BIO_dump_indent_fp(stdout, peerA->secret, peerA->secretlen, 2);
168
putchar('\n');
169
170
return 1;
171
cleanup:
172
OPENSSL_free(secret);
173
EVP_PKEY_CTX_free(derivectx);
174
return 0;
175
}
176
177
int main(void)
178
{
179
int ret = EXIT_FAILURE;
180
/* Initialise the 2 peers that will share a secret */
181
PEER_DATA peer1 = { "peer 1", "P-256" };
182
PEER_DATA peer2 = { "peer 2", "P-256" };
183
/*
184
* Setting libctx to NULL uses the default library context
185
* Use OSSL_LIB_CTX_new() to create a non default library context
186
*/
187
OSSL_LIB_CTX *libctx = NULL;
188
189
/* Each peer creates a (Ephemeral) keypair */
190
if (!create_peer(&peer1, libctx)
191
|| !create_peer(&peer2, libctx)) {
192
fprintf(stderr, "Create peer failed\n");
193
goto cleanup;
194
}
195
196
/*
197
* Each peer uses its private key and the other peers public key to
198
* derive a shared secret
199
*/
200
if (!generate_secret(&peer1, peer2.pub, libctx)
201
|| !generate_secret(&peer2, peer1.pub, libctx)) {
202
fprintf(stderr, "Generate secrets failed\n");
203
goto cleanup;
204
}
205
206
/* For illustrative purposes demonstrate that the derived secrets are equal */
207
if (peer1.secretlen != peer2.secretlen
208
|| CRYPTO_memcmp(peer1.secret, peer2.secret, peer1.secretlen) != 0) {
209
fprintf(stderr, "Derived secrets do not match\n");
210
goto cleanup;
211
} else {
212
fprintf(stdout, "Derived secrets match\n");
213
}
214
215
ret = EXIT_SUCCESS;
216
cleanup:
217
if (ret != EXIT_SUCCESS)
218
ERR_print_errors_fp(stderr);
219
destroy_peer(&peer2);
220
destroy_peer(&peer1);
221
return ret;
222
}
223
224