2 * Copyright 1995-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
11 * DSA low level APIs are deprecated for public use, but still ok for
14 #include "internal/deprecated.h"
18 #include "internal/cryptlib.h"
19 #include <openssl/bn.h>
20 #include <openssl/self_test.h>
21 #include "crypto/dsa.h"
22 #include "dsa_local.h"
24 static int dsa_keygen(DSA
*dsa
, int pairwise_test
);
25 static int dsa_keygen_pairwise_test(DSA
*dsa
, OSSL_CALLBACK
*cb
, void *cbarg
);
27 int DSA_generate_key(DSA
*dsa
)
30 if (dsa
->meth
->dsa_keygen
!= NULL
)
31 return dsa
->meth
->dsa_keygen(dsa
);
33 return dsa_keygen(dsa
, 0);
36 int dsa_generate_public_key(BN_CTX
*ctx
, const DSA
*dsa
, const BIGNUM
*priv_key
,
40 BIGNUM
*prk
= BN_new();
44 BN_with_flags(prk
, priv_key
, BN_FLG_CONSTTIME
);
46 /* pub_key = g ^ priv_key mod p */
47 if (!BN_mod_exp(pub_key
, dsa
->params
.g
, prk
, dsa
->params
.p
, ctx
))
55 static int dsa_keygen(DSA
*dsa
, int pairwise_test
)
59 BIGNUM
*pub_key
= NULL
, *priv_key
= NULL
;
61 if ((ctx
= BN_CTX_new_ex(dsa
->libctx
)) == NULL
)
64 if (dsa
->priv_key
== NULL
) {
65 if ((priv_key
= BN_secure_new()) == NULL
)
68 priv_key
= dsa
->priv_key
;
71 if (!ffc_generate_private_key(ctx
, &dsa
->params
, BN_num_bits(dsa
->params
.q
),
75 if (dsa
->pub_key
== NULL
) {
76 if ((pub_key
= BN_new()) == NULL
)
79 pub_key
= dsa
->pub_key
;
82 if (!dsa_generate_public_key(ctx
, dsa
, priv_key
, pub_key
))
85 dsa
->priv_key
= priv_key
;
86 dsa
->pub_key
= pub_key
;
90 #endif /* FIPS_MODE */
94 OSSL_CALLBACK
*cb
= NULL
;
97 OSSL_SELF_TEST_get_callback(dsa
->libctx
, &cb
, &cbarg
);
98 ok
= dsa_keygen_pairwise_test(dsa
, cb
, cbarg
);
100 BN_free(dsa
->pub_key
);
101 BN_clear_free(dsa
->priv_key
);
109 if (pub_key
!= dsa
->pub_key
)
111 if (priv_key
!= dsa
->priv_key
)
119 * FIPS 140-2 IG 9.9 AS09.33
120 * Perform a sign/verify operation.
122 static int dsa_keygen_pairwise_test(DSA
*dsa
, OSSL_CALLBACK
*cb
, void *cbarg
)
125 unsigned char dgst
[16] = {0};
126 unsigned int dgst_len
= (unsigned int)sizeof(dgst
);
128 OSSL_SELF_TEST
*st
= NULL
;
130 st
= OSSL_SELF_TEST_new(cb
, cbarg
);
134 OSSL_SELF_TEST_onbegin(st
, OSSL_SELF_TEST_TYPE_PCT
,
135 OSSL_SELF_TEST_DESC_PCT_DSA
);
137 sig
= DSA_do_sign(dgst
, (int)dgst_len
, dsa
);
141 OSSL_SELF_TEST_oncorrupt_byte(st
, dgst
);
143 if (DSA_do_verify(dgst
, dgst_len
, sig
, dsa
) != 1)
148 OSSL_SELF_TEST_onend(st
, ret
);
149 OSSL_SELF_TEST_free(st
);