2 * Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
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
10 /* DH parameters from RFC7919 and RFC3526 */
13 #include "internal/cryptlib.h"
15 #include <openssl/bn.h>
16 #include <openssl/objects.h>
17 #include "crypto/bn_dh.h"
19 static DH *dh_param_init(int nid, const BIGNUM *p, int32_t nbits)
28 /* Set q = (p - 1) / 2 (p is known to be odd so just shift right ) */
29 if (q == NULL || !BN_rshift1(q, q)) {
35 dh->params.p = (BIGNUM *)p;
36 dh->params.q = (BIGNUM *)q;
37 dh->params.g = (BIGNUM *)&_bignum_const_2;
38 /* Private key length = 2 * max_target_security_strength */
44 DH *DH_new_by_nid(int nid)
47 * The last parameter specified in these fields is
48 * 2 * max_target_security_strength.
49 * See SP800-56Ar3 Table(s) 25 & 26.
53 return dh_param_init(nid, &_bignum_ffdhe2048_p, 225);
55 return dh_param_init(nid, &_bignum_ffdhe3072_p, 275);
57 return dh_param_init(nid, &_bignum_ffdhe4096_p, 325);
59 return dh_param_init(nid, &_bignum_ffdhe6144_p, 375);
61 return dh_param_init(nid, &_bignum_ffdhe8192_p, 400);
64 return dh_param_init(nid, &_bignum_modp_1536_p, 190);
67 return dh_param_init(nid, &_bignum_modp_2048_p, 225);
69 return dh_param_init(nid, &_bignum_modp_3072_p, 275);
71 return dh_param_init(nid, &_bignum_modp_4096_p, 325);
73 return dh_param_init(nid, &_bignum_modp_6144_p, 375);
75 return dh_param_init(nid, &_bignum_modp_8192_p, 400);
77 DHerr(DH_F_DH_NEW_BY_NID, DH_R_INVALID_PARAMETER_NID);
82 int DH_get_nid(DH *dh)
84 int nid = dh->params.nid;
89 if (BN_get_word(dh->params.g) != 2)
91 if (!BN_cmp(dh->params.p, &_bignum_ffdhe2048_p))
93 else if (!BN_cmp(dh->params.p, &_bignum_ffdhe3072_p))
95 else if (!BN_cmp(dh->params.p, &_bignum_ffdhe4096_p))
97 else if (!BN_cmp(dh->params.p, &_bignum_ffdhe6144_p))
99 else if (!BN_cmp(dh->params.p, &_bignum_ffdhe8192_p))
102 else if (!BN_cmp(dh->params.p, &_bignum_modp_1536_p))
105 else if (!BN_cmp(dh->params.p, &_bignum_modp_2048_p))
107 else if (!BN_cmp(dh->params.p, &_bignum_modp_3072_p))
109 else if (!BN_cmp(dh->params.p, &_bignum_modp_4096_p))
111 else if (!BN_cmp(dh->params.p, &_bignum_modp_6144_p))
113 else if (!BN_cmp(dh->params.p, &_bignum_modp_8192_p))
118 /* Verify q is correct if it exists - reset the nid if it is not correct */
119 if (dh->params.q != NULL) {
120 BIGNUM *q = BN_dup(dh->params.p);
122 /* Check q = p * 2 + 1 we already know q is odd, so just shift right */
123 if (q == NULL || !BN_rshift1(q, q) || (BN_cmp(dh->params.q, q) != 0))
127 dh->params.nid = nid; /* cache the nid */