c93ea15b767e008f8d90b56ebdf3c5b223ec0632
[oweals/openssl.git] / crypto / dsa / dsa_key.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
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
8  */
9
10 /*
11  * DSA low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdio.h>
17 #include <time.h>
18 #include "internal/cryptlib.h"
19 #include <openssl/bn.h>
20 #include "crypto/dsa.h"
21 #include "dsa_local.h"
22
23 static int dsa_builtin_keygen(DSA *dsa);
24
25 int DSA_generate_key(DSA *dsa)
26 {
27 #ifndef FIPS_MODE
28     if (dsa->meth->dsa_keygen != NULL)
29         return dsa->meth->dsa_keygen(dsa);
30 #endif
31     return dsa_builtin_keygen(dsa);
32 }
33
34 int dsa_generate_public_key(BN_CTX *ctx, const DSA *dsa, const BIGNUM *priv_key,
35                             BIGNUM *pub_key)
36 {
37     int ret = 0;
38     BIGNUM *prk = BN_new();
39
40     if (prk == NULL)
41         return 0;
42     BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
43
44     /* pub_key = g ^ priv_key mod p */
45     if (!BN_mod_exp(pub_key, dsa->params.g, prk, dsa->params.p, ctx))
46         goto err;
47     ret = 1;
48 err:
49     BN_clear_free(prk);
50     return ret;
51 }
52
53 static int dsa_builtin_keygen(DSA *dsa)
54 {
55     int ok = 0;
56     BN_CTX *ctx = NULL;
57     BIGNUM *pub_key = NULL, *priv_key = NULL;
58
59     if ((ctx = BN_CTX_new_ex(dsa->libctx)) == NULL)
60         goto err;
61
62     if (dsa->priv_key == NULL) {
63         if ((priv_key = BN_secure_new()) == NULL)
64             goto err;
65     } else {
66         priv_key = dsa->priv_key;
67     }
68
69     if (!ffc_generate_private_key(ctx, &dsa->params, BN_num_bits(dsa->params.q),
70                                   112, priv_key))
71         goto err;
72
73     if (dsa->pub_key == NULL) {
74         if ((pub_key = BN_new()) == NULL)
75             goto err;
76     } else {
77         pub_key = dsa->pub_key;
78     }
79
80     if (!dsa_generate_public_key(ctx, dsa, priv_key, pub_key))
81         goto err;
82
83     dsa->priv_key = priv_key;
84     dsa->pub_key = pub_key;
85     dsa->dirty_cnt++;
86     ok = 1;
87
88  err:
89     if (pub_key != dsa->pub_key)
90         BN_free(pub_key);
91     if (priv_key != dsa->priv_key)
92         BN_free(priv_key);
93     BN_CTX_free(ctx);
94     return ok;
95 }