xref: /freebsd/crypto/openssl/demos/keyexch/x25519.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
1 /*
2  * Copyright 2022-2023 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 
15 /*
16  * This is a demonstration of key exchange using X25519.
17  *
18  * The variables beginning `peer1_` / `peer2_` are data which would normally be
19  * accessible to that peer.
20  *
21  * Ordinarily you would use random keys, which are demonstrated
22  * below when use_kat=0. A known answer test is demonstrated
23  * when use_kat=1.
24  */
25 
26 /* A property query used for selecting the X25519 implementation. */
27 static const char *propq = NULL;
28 
29 static const unsigned char peer1_privk_data[32] = {
30     0x80, 0x5b, 0x30, 0x20, 0x25, 0x4a, 0x70, 0x2c,
31     0xad, 0xa9, 0x8d, 0x7d, 0x47, 0xf8, 0x1b, 0x20,
32     0x89, 0xd2, 0xf9, 0x14, 0xac, 0x92, 0x27, 0xf2,
33     0x10, 0x7e, 0xdb, 0x21, 0xbd, 0x73, 0x73, 0x5d
34 };
35 
36 static const unsigned char peer2_privk_data[32] = {
37     0xf8, 0x84, 0x19, 0x69, 0x79, 0x13, 0x0d, 0xbd,
38     0xb1, 0x76, 0xd7, 0x0e, 0x7e, 0x0f, 0xb6, 0xf4,
39     0x8c, 0x4a, 0x8c, 0x5f, 0xd8, 0x15, 0x09, 0x0a,
40     0x71, 0x78, 0x74, 0x92, 0x0f, 0x85, 0xc8, 0x43
41 };
42 
43 static const unsigned char expected_result[32] = {
44     0x19, 0x71, 0x26, 0x12, 0x74, 0xb5, 0xb1, 0xce,
45     0x77, 0xd0, 0x79, 0x24, 0xb6, 0x0a, 0x5c, 0x72,
46     0x0c, 0xa6, 0x56, 0xc0, 0x11, 0xeb, 0x43, 0x11,
47     0x94, 0x3b, 0x01, 0x45, 0xca, 0x19, 0xfe, 0x09
48 };
49 
50 typedef struct peer_data_st {
51     const char *name; /* name of peer */
52     EVP_PKEY *privk; /* privk generated for peer */
53     unsigned char pubk_data[32]; /* generated pubk to send to other peer */
54 
55     unsigned char *secret; /* allocated shared secret buffer */
56     size_t secret_len;
57 } PEER_DATA;
58 
59 /*
60  * Prepare for X25519 key exchange. The public key to be sent to the remote peer
61  * is put in pubk_data, which should be a 32-byte buffer. Returns 1 on success.
62  */
keyexch_x25519_before(OSSL_LIB_CTX * libctx,const unsigned char * kat_privk_data,PEER_DATA * local_peer)63 static int keyexch_x25519_before(
64     OSSL_LIB_CTX *libctx,
65     const unsigned char *kat_privk_data,
66     PEER_DATA *local_peer)
67 {
68     int ret = 0;
69     size_t pubk_data_len = 0;
70 
71     /* Generate or load X25519 key for the peer */
72     if (kat_privk_data != NULL)
73         local_peer->privk = EVP_PKEY_new_raw_private_key_ex(libctx, "X25519", propq,
74             kat_privk_data,
75             sizeof(peer1_privk_data));
76     else
77         local_peer->privk = EVP_PKEY_Q_keygen(libctx, propq, "X25519");
78 
79     if (local_peer->privk == NULL) {
80         fprintf(stderr, "Could not load or generate private key\n");
81         goto end;
82     }
83 
84     /* Get public key corresponding to the private key */
85     if (EVP_PKEY_get_octet_string_param(local_peer->privk,
86             OSSL_PKEY_PARAM_PUB_KEY,
87             local_peer->pubk_data,
88             sizeof(local_peer->pubk_data),
89             &pubk_data_len)
90         == 0) {
91         fprintf(stderr, "EVP_PKEY_get_octet_string_param() failed\n");
92         goto end;
93     }
94 
95     /* X25519 public keys are always 32 bytes */
96     if (pubk_data_len != 32) {
97         fprintf(stderr, "EVP_PKEY_get_octet_string_param() "
98                         "yielded wrong length\n");
99         goto end;
100     }
101 
102     ret = 1;
103 end:
104     if (ret == 0) {
105         EVP_PKEY_free(local_peer->privk);
106         local_peer->privk = NULL;
107     }
108 
109     return ret;
110 }
111 
112 /*
113  * Complete X25519 key exchange. remote_peer_pubk_data should be the 32 byte
114  * public key value received from the remote peer. On success, returns 1 and the
115  * secret is pointed to by *secret. The caller must free it.
116  */
keyexch_x25519_after(OSSL_LIB_CTX * libctx,int use_kat,PEER_DATA * local_peer,const unsigned char * remote_peer_pubk_data)117 static int keyexch_x25519_after(
118     OSSL_LIB_CTX *libctx,
119     int use_kat,
120     PEER_DATA *local_peer,
121     const unsigned char *remote_peer_pubk_data)
122 {
123     int ret = 0;
124     EVP_PKEY *remote_peer_pubk = NULL;
125     EVP_PKEY_CTX *ctx = NULL;
126 
127     local_peer->secret = NULL;
128 
129     /* Load public key for remote peer. */
130     remote_peer_pubk = EVP_PKEY_new_raw_public_key_ex(libctx, "X25519", propq,
131         remote_peer_pubk_data, 32);
132     if (remote_peer_pubk == NULL) {
133         fprintf(stderr, "EVP_PKEY_new_raw_public_key_ex() failed\n");
134         goto end;
135     }
136 
137     /* Create key exchange context. */
138     ctx = EVP_PKEY_CTX_new_from_pkey(libctx, local_peer->privk, propq);
139     if (ctx == NULL) {
140         fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n");
141         goto end;
142     }
143 
144     /* Initialize derivation process. */
145     if (EVP_PKEY_derive_init(ctx) == 0) {
146         fprintf(stderr, "EVP_PKEY_derive_init() failed\n");
147         goto end;
148     }
149 
150     /* Configure each peer with the other peer's public key. */
151     if (EVP_PKEY_derive_set_peer(ctx, remote_peer_pubk) == 0) {
152         fprintf(stderr, "EVP_PKEY_derive_set_peer() failed\n");
153         goto end;
154     }
155 
156     /* Determine the secret length. */
157     if (EVP_PKEY_derive(ctx, NULL, &local_peer->secret_len) == 0) {
158         fprintf(stderr, "EVP_PKEY_derive() failed\n");
159         goto end;
160     }
161 
162     /*
163      * We are using X25519, so the secret generated will always be 32 bytes.
164      * However for exposition, the code below demonstrates a generic
165      * implementation for arbitrary lengths.
166      */
167     if (local_peer->secret_len != 32) { /* unreachable */
168         fprintf(stderr, "Secret is always 32 bytes for X25519\n");
169         goto end;
170     }
171 
172     /* Allocate memory for shared secrets. */
173     local_peer->secret = OPENSSL_malloc(local_peer->secret_len);
174     if (local_peer->secret == NULL) {
175         fprintf(stderr, "Could not allocate memory for secret\n");
176         goto end;
177     }
178 
179     /* Derive the shared secret. */
180     if (EVP_PKEY_derive(ctx, local_peer->secret,
181             &local_peer->secret_len)
182         == 0) {
183         fprintf(stderr, "EVP_PKEY_derive() failed\n");
184         goto end;
185     }
186 
187     printf("Shared secret (%s):\n", local_peer->name);
188     BIO_dump_indent_fp(stdout, local_peer->secret, local_peer->secret_len, 2);
189     putchar('\n');
190 
191     ret = 1;
192 end:
193     EVP_PKEY_CTX_free(ctx);
194     EVP_PKEY_free(remote_peer_pubk);
195     if (ret == 0) {
196         OPENSSL_clear_free(local_peer->secret, local_peer->secret_len);
197         local_peer->secret = NULL;
198     }
199 
200     return ret;
201 }
202 
keyexch_x25519(int use_kat)203 static int keyexch_x25519(int use_kat)
204 {
205     int ret = 0;
206     OSSL_LIB_CTX *libctx = NULL;
207     PEER_DATA peer1 = { "peer 1" }, peer2 = { "peer 2" };
208 
209     /*
210      * Each peer generates its private key and sends its public key
211      * to the other peer. The private key is stored locally for
212      * later use.
213      */
214     if (keyexch_x25519_before(libctx, use_kat ? peer1_privk_data : NULL,
215             &peer1)
216         == 0)
217         return 0;
218 
219     if (keyexch_x25519_before(libctx, use_kat ? peer2_privk_data : NULL,
220             &peer2)
221         == 0)
222         return 0;
223 
224     /*
225      * Each peer uses the other peer's public key to perform key exchange.
226      * After this succeeds, each peer has the same secret in its
227      * PEER_DATA.
228      */
229     if (keyexch_x25519_after(libctx, use_kat, &peer1, peer2.pubk_data) == 0)
230         return 0;
231 
232     if (keyexch_x25519_after(libctx, use_kat, &peer2, peer1.pubk_data) == 0)
233         return 0;
234 
235     /*
236      * Here we demonstrate the secrets are equal for exposition purposes.
237      *
238      * Although in practice you will generally not need to compare secrets
239      * produced through key exchange, if you do compare cryptographic secrets,
240      * always do so using a constant-time function such as CRYPTO_memcmp, never
241      * using memcmp(3).
242      */
243     if (CRYPTO_memcmp(peer1.secret, peer2.secret, peer1.secret_len) != 0) {
244         fprintf(stderr, "Negotiated secrets do not match\n");
245         goto end;
246     }
247 
248     /* If we are doing the KAT, the secret should equal our reference result. */
249     if (use_kat && CRYPTO_memcmp(peer1.secret, expected_result, peer1.secret_len) != 0) {
250         fprintf(stderr, "Did not get expected result\n");
251         goto end;
252     }
253 
254     ret = 1;
255 end:
256     /* The secrets are sensitive, so ensure they are erased before freeing. */
257     OPENSSL_clear_free(peer1.secret, peer1.secret_len);
258     OPENSSL_clear_free(peer2.secret, peer2.secret_len);
259 
260     EVP_PKEY_free(peer1.privk);
261     EVP_PKEY_free(peer2.privk);
262     OSSL_LIB_CTX_free(libctx);
263     return ret;
264 }
265 
main(int argc,char ** argv)266 int main(int argc, char **argv)
267 {
268     /* Test X25519 key exchange with known result. */
269     printf("Key exchange using known answer (deterministic):\n");
270     if (keyexch_x25519(1) == 0)
271         return EXIT_FAILURE;
272 
273     /* Test X25519 key exchange with random keys. */
274     printf("Key exchange using random keys:\n");
275     if (keyexch_x25519(0) == 0)
276         return EXIT_FAILURE;
277 
278     return EXIT_SUCCESS;
279 }
280