2 * Copyright 1995-2016 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
12 #include "internal/cryptlib.h"
13 #include <openssl/bn.h>
14 #include "crypto/dsa.h"
15 #include "dsa_local.h"
17 static int dsa_builtin_keygen(OPENSSL_CTX *libctx, DSA *dsa);
19 int DSA_generate_key(DSA *dsa)
21 if (dsa->meth->dsa_keygen != NULL)
22 return dsa->meth->dsa_keygen(dsa);
23 return dsa_builtin_keygen(NULL, dsa);
26 int dsa_generate_key_ctx(OPENSSL_CTX *libctx, DSA *dsa)
29 if (dsa->meth->dsa_keygen != NULL)
30 return dsa->meth->dsa_keygen(dsa);
32 return dsa_builtin_keygen(libctx, dsa);
35 static int dsa_builtin_keygen(OPENSSL_CTX *libctx, DSA *dsa)
39 BIGNUM *pub_key = NULL, *priv_key = NULL;
41 if ((ctx = BN_CTX_new_ex(libctx)) == NULL)
44 if (dsa->priv_key == NULL) {
45 if ((priv_key = BN_secure_new()) == NULL)
48 priv_key = dsa->priv_key;
51 if (!ffc_generate_private_key(ctx, &dsa->params, BN_num_bits(dsa->params.q),
55 if (dsa->pub_key == NULL) {
56 if ((pub_key = BN_new()) == NULL)
59 pub_key = dsa->pub_key;
63 BIGNUM *prk = BN_new();
67 BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
69 /* pub_key = g ^ priv_key mod p */
70 if (!BN_mod_exp(pub_key, dsa->params.g, prk, dsa->params.p, ctx)) {
74 /* We MUST free prk before any further use of priv_key */
78 dsa->priv_key = priv_key;
79 dsa->pub_key = pub_key;
84 if (pub_key != dsa->pub_key)
86 if (priv_key != dsa->priv_key)