GH587: Extend ECDH tests to more curves. Add more ECDH KATs.
[openssl.git] / test / ecdhtest.c
1 /* ====================================================================
2  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
3  *
4  * The Elliptic Curve Public-Key Crypto Library (ECC Code) included
5  * herein is developed by SUN MICROSYSTEMS, INC., and is contributed
6  * to the OpenSSL project.
7  *
8  * The ECC Code is licensed pursuant to the OpenSSL open source
9  * license provided below.
10  *
11  * The ECDH software is originally written by Douglas Stebila of
12  * Sun Microsystems Laboratories.
13  *
14  */
15 /* ====================================================================
16  * Copyright (c) 1998-2003 The OpenSSL Project.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  *
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  *
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in
27  *    the documentation and/or other materials provided with the
28  *    distribution.
29  *
30  * 3. All advertising materials mentioning features or use of this
31  *    software must display the following acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
34  *
35  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
36  *    endorse or promote products derived from this software without
37  *    prior written permission. For written permission, please contact
38  *    openssl-core@openssl.org.
39  *
40  * 5. Products derived from this software may not be called "OpenSSL"
41  *    nor may "OpenSSL" appear in their names without prior written
42  *    permission of the OpenSSL Project.
43  *
44  * 6. Redistributions of any form whatsoever must retain the following
45  *    acknowledgment:
46  *    "This product includes software developed by the OpenSSL Project
47  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
50  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
52  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
53  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
54  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
56  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
58  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
59  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
60  * OF THE POSSIBILITY OF SUCH DAMAGE.
61  * ====================================================================
62  *
63  * This product includes cryptographic software written by Eric Young
64  * (eay@cryptsoft.com).  This product includes software written by Tim
65  * Hudson (tjh@cryptsoft.com).
66  *
67  */
68
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72
73 #include "../e_os.h"
74
75 #include <openssl/opensslconf.h> /* for OPENSSL_NO_EC */
76 #include <openssl/crypto.h>
77 #include <openssl/bio.h>
78 #include <openssl/bn.h>
79 #include <openssl/objects.h>
80 #include <openssl/rand.h>
81 #include <openssl/sha.h>
82 #include <openssl/err.h>
83
84 #ifdef OPENSSL_NO_EC
85 int main(int argc, char *argv[])
86 {
87     printf("No ECDH support\n");
88     return (0);
89 }
90 #else
91 # include <openssl/ec.h>
92
93 static const char rnd_seed[] =
94     "string to make the random number generator think it has entropy";
95
96 static const int KDF1_SHA1_len = 20;
97 static void *KDF1_SHA1(const void *in, size_t inlen, void *out,
98                        size_t *outlen)
99 {
100     if (*outlen < SHA_DIGEST_LENGTH)
101         return NULL;
102     *outlen = SHA_DIGEST_LENGTH;
103     return SHA1(in, inlen, out);
104 }
105
106 static int test_ecdh_curve(int nid, BN_CTX *ctx, BIO *out)
107 {
108     EC_KEY *a = NULL;
109     EC_KEY *b = NULL;
110     BIGNUM *x_a = NULL, *y_a = NULL, *x_b = NULL, *y_b = NULL;
111     char buf[12];
112     unsigned char *abuf = NULL, *bbuf = NULL;
113     int i, alen, blen, aout, bout, ret = 0;
114     const EC_GROUP *group;
115
116     a = EC_KEY_new_by_curve_name(nid);
117     b = EC_KEY_new_by_curve_name(nid);
118     if (a == NULL || b == NULL)
119         goto err;
120
121     group = EC_KEY_get0_group(a);
122
123     if ((x_a = BN_new()) == NULL)
124         goto err;
125     if ((y_a = BN_new()) == NULL)
126         goto err;
127     if ((x_b = BN_new()) == NULL)
128         goto err;
129     if ((y_b = BN_new()) == NULL)
130         goto err;
131
132     BIO_puts(out, "Testing key generation with ");
133     BIO_puts(out, OBJ_nid2sn(nid));
134 # ifdef NOISY
135     BIO_puts(out, "\n");
136 # else
137     (void)BIO_flush(out);
138 # endif
139
140     if (!EC_KEY_generate_key(a))
141         goto err;
142
143     if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) ==
144         NID_X9_62_prime_field) {
145         if (!EC_POINT_get_affine_coordinates_GFp
146             (group, EC_KEY_get0_public_key(a), x_a, y_a, ctx))
147             goto err;
148     }
149 # ifndef OPENSSL_NO_EC2M
150     else {
151         if (!EC_POINT_get_affine_coordinates_GF2m(group,
152                                                   EC_KEY_get0_public_key(a),
153                                                   x_a, y_a, ctx))
154             goto err;
155     }
156 # endif
157 # ifdef NOISY
158     BIO_puts(out, "  pri 1=");
159     BN_print(out, a->priv_key);
160     BIO_puts(out, "\n  pub 1=");
161     BN_print(out, x_a);
162     BIO_puts(out, ",");
163     BN_print(out, y_a);
164     BIO_puts(out, "\n");
165 # else
166     BIO_printf(out, " .");
167     (void)BIO_flush(out);
168 # endif
169
170     if (!EC_KEY_generate_key(b))
171         goto err;
172
173     if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) ==
174         NID_X9_62_prime_field) {
175         if (!EC_POINT_get_affine_coordinates_GFp
176             (group, EC_KEY_get0_public_key(b), x_b, y_b, ctx))
177             goto err;
178     }
179 # ifndef OPENSSL_NO_EC2M
180     else {
181         if (!EC_POINT_get_affine_coordinates_GF2m(group,
182                                                   EC_KEY_get0_public_key(b),
183                                                   x_b, y_b, ctx))
184             goto err;
185     }
186 # endif
187
188 # ifdef NOISY
189     BIO_puts(out, "  pri 2=");
190     BN_print(out, b->priv_key);
191     BIO_puts(out, "\n  pub 2=");
192     BN_print(out, x_b);
193     BIO_puts(out, ",");
194     BN_print(out, y_b);
195     BIO_puts(out, "\n");
196 # else
197     BIO_printf(out, ".");
198     (void)BIO_flush(out);
199 # endif
200
201     alen = KDF1_SHA1_len;
202     abuf = OPENSSL_malloc(alen);
203     aout =
204         ECDH_compute_key(abuf, alen, EC_KEY_get0_public_key(b), a, KDF1_SHA1);
205
206 # ifdef NOISY
207     BIO_puts(out, "  key1 =");
208     for (i = 0; i < aout; i++) {
209         sprintf(buf, "%02X", abuf[i]);
210         BIO_puts(out, buf);
211     }
212     BIO_puts(out, "\n");
213 # else
214     BIO_printf(out, ".");
215     (void)BIO_flush(out);
216 # endif
217
218     blen = KDF1_SHA1_len;
219     bbuf = OPENSSL_malloc(blen);
220     bout =
221         ECDH_compute_key(bbuf, blen, EC_KEY_get0_public_key(a), b, KDF1_SHA1);
222
223 # ifdef NOISY
224     BIO_puts(out, "  key2 =");
225     for (i = 0; i < bout; i++) {
226         sprintf(buf, "%02X", bbuf[i]);
227         BIO_puts(out, buf);
228     }
229     BIO_puts(out, "\n");
230 # else
231     BIO_printf(out, ".");
232     (void)BIO_flush(out);
233 # endif
234
235     if ((aout < 4) || (bout != aout) || (memcmp(abuf, bbuf, aout) != 0)) {
236 # ifndef NOISY
237         BIO_printf(out, " failed\n\n");
238         BIO_printf(out, "key a:\n");
239         BIO_printf(out, "private key: ");
240         BN_print(out, EC_KEY_get0_private_key(a));
241         BIO_printf(out, "\n");
242         BIO_printf(out, "public key (x,y): ");
243         BN_print(out, x_a);
244         BIO_printf(out, ",");
245         BN_print(out, y_a);
246         BIO_printf(out, "\nkey b:\n");
247         BIO_printf(out, "private key: ");
248         BN_print(out, EC_KEY_get0_private_key(b));
249         BIO_printf(out, "\n");
250         BIO_printf(out, "public key (x,y): ");
251         BN_print(out, x_b);
252         BIO_printf(out, ",");
253         BN_print(out, y_b);
254         BIO_printf(out, "\n");
255         BIO_printf(out, "generated key a: ");
256         for (i = 0; i < bout; i++) {
257             sprintf(buf, "%02X", bbuf[i]);
258             BIO_puts(out, buf);
259         }
260         BIO_printf(out, "\n");
261         BIO_printf(out, "generated key b: ");
262         for (i = 0; i < aout; i++) {
263             sprintf(buf, "%02X", abuf[i]);
264             BIO_puts(out, buf);
265         }
266         BIO_printf(out, "\n");
267 # endif
268         fprintf(stderr, "Error in ECDH routines\n");
269         ret = 0;
270     } else {
271 # ifndef NOISY
272         BIO_printf(out, " ok\n");
273 # endif
274         ret = 1;
275     }
276  err:
277     ERR_print_errors_fp(stderr);
278
279     OPENSSL_free(abuf);
280     OPENSSL_free(bbuf);
281     BN_free(x_a);
282     BN_free(y_a);
283     BN_free(x_b);
284     BN_free(y_b);
285     EC_KEY_free(b);
286     EC_KEY_free(a);
287     return (ret);
288 }
289
290 typedef struct {
291     const int nid;
292     const char *da;
293     const char *db;
294     const char *Z;
295 } ecdh_kat_t;
296
297 static const ecdh_kat_t ecdh_kats[] = {
298     /* Keys and shared secrets from RFC 5114 */
299     { NID_X9_62_prime192v1,
300     "323FA3169D8E9C6593F59476BC142000AB5BE0E249C43426",
301     "631F95BB4A67632C9C476EEE9AB695AB240A0499307FCF62",
302     "AD420182633F8526BFE954ACDA376F05E5FF4F837F54FEBE" },
303     { NID_secp224r1,
304     "B558EB6C288DA707BBB4F8FBAE2AB9E9CB62E3BC5C7573E22E26D37F",
305     "AC3B1ADD3D9770E6F6A708EE9F3B8E0AB3B480E9F27F85C88B5E6D18",
306     "52272F50F46F4EDC9151569092F46DF2D96ECC3B6DC1714A4EA949FA" },
307     { NID_X9_62_prime256v1,
308     "814264145F2F56F2E96A8E337A1284993FAF432A5ABCE59E867B7291D507A3AF",
309     "2CE1788EC197E096DB95A200CC0AB26A19CE6BCCAD562B8EEE1B593761CF7F41",
310     "DD0F5396219D1EA393310412D19A08F1F5811E9DC8EC8EEA7F80D21C820C2788" },
311     { NID_secp384r1,
312     "D27335EA71664AF244DD14E9FD1260715DFD8A7965571C48D709EE7A7962A156"
313     "D706A90CBCB5DF2986F05FEADB9376F1",
314     "52D1791FDB4B70F89C0F00D456C2F7023B6125262C36A7DF1F80231121CCE3D3"
315     "9BE52E00C194A4132C4A6C768BCD94D2",
316     "5EA1FC4AF7256D2055981B110575E0A8CAE53160137D904C59D926EB1B8456E4"
317     "27AA8A4540884C37DE159A58028ABC0E" },
318     { NID_secp521r1,
319     "0113F82DA825735E3D97276683B2B74277BAD27335EA71664AF2430CC4F33459"
320     "B9669EE78B3FFB9B8683015D344DCBFEF6FB9AF4C6C470BE254516CD3C1A1FB4"
321     "7362",
322     "00CEE3480D8645A17D249F2776D28BAE616952D1791FDB4B70F7C3378732AA1B"
323     "22928448BCD1DC2496D435B01048066EBE4F72903C361B1A9DC1193DC2C9D089"
324     "1B96",
325     "00CDEA89621CFA46B132F9E4CFE2261CDE2D4368EB5656634C7CC98C7A00CDE5"
326     "4ED1866A0DD3E6126C9D2F845DAFF82CEB1DA08F5D87521BB0EBECA77911169C"
327     "20CC" },
328     /* Keys and shared secrets from RFC 5903 */
329     { NID_X9_62_prime256v1,
330     "C88F01F510D9AC3F70A292DAA2316DE544E9AAB8AFE84049C62A9C57862D1433",
331     "C6EF9C5D78AE012A011164ACB397CE2088685D8F06BF9BE0B283AB46476BEE53",
332     "D6840F6B42F6EDAFD13116E0E12565202FEF8E9ECE7DCE03812464D04B9442DE" },
333     { NID_secp384r1,
334     "099F3C7034D4A2C699884D73A375A67F7624EF7C6B3C0F160647B67414DCE655"
335     "E35B538041E649EE3FAEF896783AB194",
336     "41CB0779B4BDB85D47846725FBEC3C9430FAB46CC8DC5060855CC9BDA0AA2942"
337     "E0308312916B8ED2960E4BD55A7448FC",
338     "11187331C279962D93D604243FD592CB9D0A926F422E47187521287E7156C5C4"
339     "D603135569B9E9D09CF5D4A270F59746" },
340     { NID_secp521r1,
341     "0037ADE9319A89F4DABDB3EF411AACCCA5123C61ACAB57B5393DCE47608172A0"
342     "95AA85A30FE1C2952C6771D937BA9777F5957B2639BAB072462F68C27A57382D"
343     "4A52",
344     "0145BA99A847AF43793FDD0E872E7CDFA16BE30FDC780F97BCCC3F078380201E"
345     "9C677D600B343757A3BDBF2A3163E4C2F869CCA7458AA4A4EFFC311F5CB15168"
346     "5EB9",
347     "01144C7D79AE6956BC8EDB8E7C787C4521CB086FA64407F97894E5E6B2D79B04"
348     "D1427E73CA4BAA240A34786859810C06B3C715A3A8CC3151F2BEE417996D19F3"
349     "DDEA" },
350     /* Keys and shared secrets from RFC 7027 */
351     { NID_brainpoolP256r1,
352     "81DB1EE100150FF2EA338D708271BE38300CB54241D79950F77B063039804F1D",
353     "55E40BC41E37E3E2AD25C3C6654511FFA8474A91A0032087593852D3E7D76BD3",
354     "89AFC39D41D3B327814B80940B042590F96556EC91E6AE7939BCE31F3A18BF2B" },
355     { NID_brainpoolP384r1,
356     "1E20F5E048A5886F1F157C74E91BDE2B98C8B52D58E5003D57053FC4B0BD65D6"
357     "F15EB5D1EE1610DF870795143627D042",
358     "032640BC6003C59260F7250C3DB58CE647F98E1260ACCE4ACDA3DD869F74E01F"
359     "8BA5E0324309DB6A9831497ABAC96670",
360     "0BD9D3A7EA0B3D519D09D8E48D0785FB744A6B355E6304BC51C229FBBCE239BB"
361     "ADF6403715C35D4FB2A5444F575D4F42" },
362     { NID_brainpoolP512r1,
363     "16302FF0DBBB5A8D733DAB7141C1B45ACBC8715939677F6A56850A38BD87BD59"
364     "B09E80279609FF333EB9D4C061231FB26F92EEB04982A5F1D1764CAD57665422",
365     "230E18E1BCC88A362FA54E4EA3902009292F7F8033624FD471B5D8ACE49D12CF"
366     "ABBC19963DAB8E2F1EBA00BFFB29E4D72D13F2224562F405CB80503666B25429",
367     "A7927098655F1F9976FA50A9D566865DC530331846381C87256BAF3226244B76"
368     "D36403C024D7BBF0AA0803EAFF405D3D24F11A9B5C0BEF679FE1454B21C4CD1F" }
369 };
370
371 /* Given private value and NID, create EC_KEY structure */
372
373 static EC_KEY *mk_eckey(int nid, const char *str)
374 {
375     int ok = 0;
376     EC_KEY *k = NULL;
377     BIGNUM *priv = NULL;
378     EC_POINT *pub = NULL;
379     const EC_GROUP *grp;
380     k = EC_KEY_new_by_curve_name(nid);
381     if (!k)
382         goto err;
383     if(!BN_hex2bn(&priv, str))
384         goto err;
385     if (!priv)
386         goto err;
387     if (!EC_KEY_set_private_key(k, priv))
388         goto err;
389     grp = EC_KEY_get0_group(k);
390     pub = EC_POINT_new(grp);
391     if (!pub)
392         goto err;
393     if (!EC_POINT_mul(grp, pub, priv, NULL, NULL, NULL))
394         goto err;
395     if (!EC_KEY_set_public_key(k, pub))
396         goto err;
397     ok = 1;
398  err:
399     BN_clear_free(priv);
400     EC_POINT_free(pub);
401     if (ok)
402         return k;
403     EC_KEY_free(k);
404     return NULL;
405 }
406
407 /*
408  * Known answer test: compute shared secret and check it matches expected
409  * value.
410  */
411
412 static int ecdh_kat(BIO *out, const ecdh_kat_t *kat)
413 {
414     int rv = 0;
415     EC_KEY *key1 = NULL, *key2 = NULL;
416     BIGNUM *bnz = NULL;
417     unsigned char *Ztmp = NULL, *Z = NULL;
418     size_t Ztmplen, Zlen;
419     BIO_puts(out, "Testing ECDH shared secret with ");
420     BIO_puts(out, OBJ_nid2sn(kat->nid));
421     if(!BN_hex2bn(&bnz, kat->Z))
422         goto err;
423     key1 = mk_eckey(kat->nid, kat->da);
424     key2 = mk_eckey(kat->nid, kat->db);
425     if (!key1 || !key2)
426         goto err;
427     Ztmplen = (EC_GROUP_get_degree(EC_KEY_get0_group(key1)) + 7) / 8;
428     Zlen = BN_num_bytes(bnz);
429     if (Zlen > Ztmplen)
430         goto err;
431     if((Ztmp = OPENSSL_zalloc(Ztmplen)) == NULL)
432         goto err;
433     if((Z = OPENSSL_zalloc(Ztmplen)) == NULL)
434         goto err;
435     /* Z offset compensates for bn2bin stripping leading 0x00 bytes */
436     if(!BN_bn2bin(bnz, Z + Ztmplen - Zlen))
437         goto err;
438     if (!ECDH_compute_key(Ztmp, Ztmplen,
439                           EC_KEY_get0_public_key(key2), key1, 0))
440         goto err;
441     if (memcmp(Ztmp, Z, Ztmplen))
442         goto err;
443     memset(Ztmp, 0, Ztmplen);
444     if (!ECDH_compute_key(Ztmp, Ztmplen,
445                           EC_KEY_get0_public_key(key1), key2, 0))
446         goto err;
447     if (memcmp(Ztmp, Z, Ztmplen))
448         goto err;
449     rv = 1;
450  err:
451     EC_KEY_free(key1);
452     EC_KEY_free(key2);
453     OPENSSL_free(Ztmp);
454     OPENSSL_free(Z);
455     BN_free(bnz);
456     if (rv)
457         BIO_puts(out, " ok\n");
458     else {
459         fprintf(stderr, "Error in ECDH routines\n");
460         ERR_print_errors_fp(stderr);
461     }
462     return rv;
463 }
464
465 int main(int argc, char *argv[])
466 {
467     BN_CTX *ctx = NULL;
468     int nid, ret = 1;
469     EC_builtin_curve *curves = NULL;
470     size_t crv_len = 0, n = 0;
471     BIO *out;
472
473     CRYPTO_set_mem_debug(1);
474     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
475
476     RAND_seed(rnd_seed, sizeof rnd_seed);
477
478     out = BIO_new(BIO_s_file());
479     if (out == NULL)
480         EXIT(1);
481     BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT);
482
483     if ((ctx = BN_CTX_new()) == NULL)
484         goto err;
485
486     /* get a list of all internal curves */
487     crv_len = EC_get_builtin_curves(NULL, 0);
488     curves = OPENSSL_malloc(sizeof(*curves) * crv_len);
489     if (curves == NULL) goto err;
490
491     if (!EC_get_builtin_curves(curves, crv_len)) goto err;
492
493     /* NAMED CURVES TESTS */
494     for (n = 0; n < crv_len; n++) {
495         nid = curves[n].nid;
496         if (!test_ecdh_curve(nid, ctx, out)) goto err;
497     }
498
499     /* KATs */
500     for (n = 0; n < (sizeof(ecdh_kats)/sizeof(ecdh_kat_t)); n++) {
501         if (!ecdh_kat(out, &ecdh_kats[n]))
502             goto err;
503     }
504
505     ret = 0;
506
507  err:
508     ERR_print_errors_fp(stderr);
509     OPENSSL_free(curves);
510     BN_CTX_free(ctx);
511     BIO_free(out);
512     CRYPTO_cleanup_all_ex_data();
513     ERR_remove_thread_state(NULL);
514 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
515     if (CRYPTO_mem_leaks_fp(stderr) <= 0)
516         ret = 1;
517 #endif
518     EXIT(ret);
519 }
520 #endif