Simplify dsa_ossl.c
[openssl.git] / crypto / dsa / dsa_key.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 <stdio.h>
11 #include <time.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/bn.h>
14 #include "dsa_locl.h"
15 #include <openssl/rand.h>
16
17 static int dsa_builtin_keygen(DSA *dsa);
18
19 int DSA_generate_key(DSA *dsa)
20 {
21     if (dsa->meth->dsa_keygen)
22         return dsa->meth->dsa_keygen(dsa);
23     return dsa_builtin_keygen(dsa);
24 }
25
26 static int dsa_builtin_keygen(DSA *dsa)
27 {
28     int ok = 0;
29     BN_CTX *ctx = NULL;
30     BIGNUM *pub_key = NULL, *priv_key = NULL;
31
32     if ((ctx = BN_CTX_new()) == NULL)
33         goto err;
34
35     if (dsa->priv_key == NULL) {
36         if ((priv_key = BN_secure_new()) == NULL)
37             goto err;
38     } else
39         priv_key = dsa->priv_key;
40
41     do
42         if (!BN_rand_range(priv_key, dsa->q))
43             goto err;
44     while (BN_is_zero(priv_key)) ;
45
46     if (dsa->pub_key == NULL) {
47         if ((pub_key = BN_new()) == NULL)
48             goto err;
49     } else
50         pub_key = dsa->pub_key;
51
52     {
53         BIGNUM *local_prk = NULL;
54         BIGNUM *prk;
55
56         if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
57             local_prk = prk = BN_new();
58             if (local_prk == NULL)
59                 goto err;
60             BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
61         } else {
62             prk = priv_key;
63         }
64
65         if (!BN_mod_exp(pub_key, dsa->g, prk, dsa->p, ctx)) {
66             BN_free(local_prk);
67             goto err;
68         }
69         /* We MUST free local_prk before any further use of priv_key */
70         BN_free(local_prk);
71     }
72
73     dsa->priv_key = priv_key;
74     dsa->pub_key = pub_key;
75     ok = 1;
76
77  err:
78     if (pub_key != dsa->pub_key)
79         BN_free(pub_key);
80     if (priv_key != dsa->priv_key)
81         BN_free(priv_key);
82     BN_CTX_free(ctx);
83     return (ok);
84 }