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