]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/ffc/ffc_key_generate.c
078e8d39a105854452074af64f241aa84ed8f186
[thirdparty/openssl.git] / crypto / ffc / ffc_key_generate.c
1 /*
2 * Copyright 2019-2020 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 "internal/ffc.h"
11
12 /*
13 * SP800-56Ar3 5.6.1.1.4 Key pair generation by testing candidates.
14 * Generates a private key in the interval [1, min(2 ^ N - 1, q - 1)].
15 *
16 * ctx must be set up with a libctx (for fips mode).
17 * params contains the FFC domain parameters p, q and g (for DH or DSA).
18 * N is the maximum bit length of the generated private key,
19 * s is the security strength.
20 * priv_key is the returned private key,
21 */
22 int ffc_generate_private_key(BN_CTX *ctx, const FFC_PARAMS *params,
23 int N, int s, BIGNUM *priv)
24 {
25 #ifdef FIPS_MODE
26 return ffc_generate_private_key_fips(ctx, params, N, s, priv);
27 #else
28 do {
29 if (!BN_priv_rand_range_ex(priv, params->q, ctx))
30 return 0;
31 } while (BN_is_zero(priv) || BN_is_one(priv));
32 return 1;
33 #endif /* FIPS_MODE */
34 }
35
36 int ffc_generate_private_key_fips(BN_CTX *ctx, const FFC_PARAMS *params,
37 int N, int s, BIGNUM *priv)
38 {
39 int ret = 0, qbits = BN_num_bits(params->q);
40 BIGNUM *m, *two_powN = NULL;
41
42 /* Step (2) : check range of N */
43 if (N < 2 * s || N > qbits)
44 return 0;
45
46 /* Deal with the edge case where the value of N is not set */
47 if (N == 0) {
48 N = qbits;
49 s = N / 2;
50 }
51
52 two_powN = BN_new();
53 /* 2^N */
54 if (two_powN == NULL || !BN_lshift(two_powN, BN_value_one(), N))
55 goto err;
56
57 /* Step (5) : M = min(2 ^ N, q) */
58 m = (BN_cmp(two_powN, params->q) > 0) ? params->q : two_powN;
59
60 do {
61 /* Steps (3, 4 & 7) : c + 1 = 1 + random[0..2^N - 1] */
62 if (!BN_priv_rand_range_ex(priv, two_powN, ctx)
63 || !BN_add_word(priv, 1))
64 goto err;
65 /* Step (6) : loop if c > M - 2 (i.e. c + 1 >= M) */
66 if (BN_cmp(priv, m) < 0)
67 break;
68 } while (1);
69
70 ret = 1;
71 err:
72 BN_free(two_powN);
73 return ret;
74 }