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 * DH low level APIs are deprecated for public use, but still ok for
16 #include "internal/deprecated.h"
19 #include "internal/cryptlib.h"
21 #include <openssl/bn.h>
22 #include <openssl/objects.h>
23 #include "crypto/bn_dh.h"
24 #include "crypto/dh.h"
25 #include "crypto/security_bits.h"
28 #define FFDHE(sz) { NID_ffdhe##sz, sz, &_bignum_ffdhe##sz##_p }
29 #define MODP(sz) { NID_modp_##sz, sz, &_bignum_modp_##sz##_p }
31 typedef struct safe_prime_group_st
{
37 static const SP_GROUP sp_groups
[] = {
54 static DH
*dh_new_by_nid_with_ctx(OPENSSL_CTX
*libctx
, int nid
);
56 static DH
*dh_param_init(OPENSSL_CTX
*libctx
, int nid
, const BIGNUM
*p
,
60 DH
*dh
= dh_new_with_ctx(libctx
);
66 /* Set q = (p - 1) / 2 (p is known to be odd so just shift right ) */
67 if (q
== NULL
|| !BN_rshift1(q
, q
)) {
73 dh
->params
.p
= (BIGNUM
*)p
;
74 dh
->params
.q
= (BIGNUM
*)q
;
75 dh
->params
.g
= (BIGNUM
*)&_bignum_const_2
;
76 /* Private key length = 2 * max_target_security_strength */
82 static DH
*dh_new_by_nid_with_ctx(OPENSSL_CTX
*libctx
, int nid
)
86 for (i
= 0; i
< (int)OSSL_NELEM(sp_groups
); ++i
) {
87 if (sp_groups
[i
].nid
== nid
) {
88 int max_target_security_strength
=
89 ifc_ffc_compute_security_bits(sp_groups
[i
].nbits
);
92 * The last parameter specified here is
93 * 2 * max_target_security_strength.
94 * See SP800-56Ar3 Table(s) 25 & 26.
96 return dh_param_init(libctx
, nid
, sp_groups
[i
].p
,
97 2 * max_target_security_strength
);
100 DHerr(0, DH_R_INVALID_PARAMETER_NID
);
104 DH
*DH_new_by_nid(int nid
)
106 return dh_new_by_nid_with_ctx(NULL
, nid
);
110 int DH_get_nid(DH
*dh
)
118 nid
= dh
->params
.nid
;
119 /* Just return if it is already cached */
120 if (nid
!= NID_undef
)
123 if (BN_get_word(dh
->params
.g
) != 2)
126 for (i
= 0; i
< (int)OSSL_NELEM(sp_groups
); ++i
) {
127 /* If a matching p is found then we will break out of the loop */
128 if (!BN_cmp(dh
->params
.p
, sp_groups
[i
].p
)) {
129 /* Set q = (p - 1) / 2 (p is known to be odd so just shift right ) */
130 q
= BN_dup(dh
->params
.p
);
132 if (q
== NULL
|| !BN_rshift1(q
, q
))
133 break; /* returns nid = NID_undef on failure */
135 /* Verify q is correct if it exists */
136 if (dh
->params
.q
!= NULL
) {
137 if (BN_cmp(dh
->params
.q
, q
) != 0)
138 break; /* returns nid = NID_undef if q does not match */
140 /* assign the calculated q */
142 q
= NULL
; /* set to NULL so it is not freed */
144 dh
->params
.nid
= sp_groups
[i
].nid
; /* cache the nid */
145 dh
->length
= 2 * ifc_ffc_compute_security_bits(sp_groups
[i
].nbits
);