Deprecate the low level DSA functions.
[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(OPENSSL_CTX *libctx, DSA *dsa);
24
25 int DSA_generate_key(DSA *dsa)
26 {
27     if (dsa->meth->dsa_keygen != NULL)
28         return dsa->meth->dsa_keygen(dsa);
29     return dsa_builtin_keygen(NULL, dsa);
30 }
31
32 int dsa_generate_key_ctx(OPENSSL_CTX *libctx, DSA *dsa)
33 {
34 #ifndef FIPS_MODE
35     if (dsa->meth->dsa_keygen != NULL)
36         return dsa->meth->dsa_keygen(dsa);
37 #endif
38     return dsa_builtin_keygen(libctx, dsa);
39 }
40
41 static int dsa_builtin_keygen(OPENSSL_CTX *libctx, DSA *dsa)
42 {
43     int ok = 0;
44     BN_CTX *ctx = NULL;
45     BIGNUM *pub_key = NULL, *priv_key = NULL;
46
47     if ((ctx = BN_CTX_new_ex(libctx)) == NULL)
48         goto err;
49
50     if (dsa->priv_key == NULL) {
51         if ((priv_key = BN_secure_new()) == NULL)
52             goto err;
53     } else {
54         priv_key = dsa->priv_key;
55     }
56
57     if (!ffc_generate_private_key(ctx, &dsa->params, BN_num_bits(dsa->params.q),
58                                   112, priv_key))
59         goto err;
60
61     if (dsa->pub_key == NULL) {
62         if ((pub_key = BN_new()) == NULL)
63             goto err;
64     } else {
65         pub_key = dsa->pub_key;
66     }
67
68     {
69         BIGNUM *prk = BN_new();
70
71         if (prk == NULL)
72             goto err;
73         BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
74
75         /* pub_key = g ^ priv_key mod p */
76         if (!BN_mod_exp(pub_key, dsa->params.g, prk, dsa->params.p, ctx)) {
77             BN_free(prk);
78             goto err;
79         }
80         /* We MUST free prk before any further use of priv_key */
81         BN_free(prk);
82     }
83
84     dsa->priv_key = priv_key;
85     dsa->pub_key = pub_key;
86     dsa->dirty_cnt++;
87     ok = 1;
88
89  err:
90     if (pub_key != dsa->pub_key)
91         BN_free(pub_key);
92     if (priv_key != dsa->priv_key)
93         BN_free(priv_key);
94     BN_CTX_free(ctx);
95     return ok;
96 }