1 /* $OpenBSD: bn_mont.c,v 1.2 2022/12/06 18:23:29 tb Exp $ */
2
3 /*
4 * Copyright (c) 2014 Miodrag Vallat.
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <err.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22
23 #include <openssl/bn.h>
24 #include <openssl/crypto.h>
25 #include <openssl/dh.h>
26 #include <openssl/err.h>
27
28 /*
29 * Test for proper bn_mul_mont behaviour when operands are of vastly different
30 * sizes.
31 */
32
33 int
main(int argc,char * argv[])34 main(int argc, char *argv[])
35 {
36 DH *dh = NULL;
37 BIGNUM *priv_key = NULL;
38 unsigned char *key = NULL;
39 unsigned char r[32 + 16 * 8];
40 size_t privsz;
41
42 arc4random_buf(r, sizeof(r));
43
44 for (privsz = 32; privsz <= sizeof(r); privsz += 8) {
45 dh = DH_new();
46 if (dh == NULL)
47 goto err;
48 if (DH_generate_parameters_ex(dh, 32, DH_GENERATOR_2,
49 NULL) == 0)
50 goto err;
51
52 /* force private key to be much larger than public one */
53 priv_key = BN_bin2bn(r, privsz, NULL);
54 if (priv_key == NULL)
55 goto err;
56
57 if (!DH_set0_key(dh, NULL, priv_key))
58 goto err;
59 priv_key = NULL;
60
61 if (DH_generate_key(dh) == 0)
62 goto err;
63 key = malloc(DH_size(dh));
64 if (key == NULL)
65 err(1, "malloc");
66 if (DH_compute_key(key, DH_get0_pub_key(dh), dh) == -1)
67 goto err;
68
69 free(key);
70 key = NULL;
71 DH_free(dh);
72 dh = NULL;
73 }
74
75 return 0;
76
77 err:
78 ERR_print_errors_fp(stderr);
79 free(key);
80 BN_free(priv_key);
81 DH_free(dh);
82 return 1;
83 }
84