]> git.ipfire.org Git - thirdparty/openssl.git/blame - crypto/dsa/dsa_key.c
Implement DSA in the default provider
[thirdparty/openssl.git] / crypto / dsa / dsa_key.c
CommitLineData
d2e9e320
RS
1/*
2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
d02b48c6 3 *
3cdbea65 4 * Licensed under the Apache License 2.0 (the "License"). You may not use
d2e9e320
RS
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
d02b48c6
RE
8 */
9
10#include <stdio.h>
11#include <time.h>
b39fc560 12#include "internal/cryptlib.h"
474e469b 13#include <openssl/bn.h>
1258396d 14#include "dsa_locl.h"
d02b48c6 15
0e4aa0d2
GT
16static int dsa_builtin_keygen(DSA *dsa);
17
6b691a5c 18int DSA_generate_key(DSA *dsa)
0f113f3e
MC
19{
20 if (dsa->meth->dsa_keygen)
21 return dsa->meth->dsa_keygen(dsa);
22 return dsa_builtin_keygen(dsa);
23}
0e4aa0d2
GT
24
25static int dsa_builtin_keygen(DSA *dsa)
0f113f3e
MC
26{
27 int ok = 0;
28 BN_CTX *ctx = NULL;
29 BIGNUM *pub_key = NULL, *priv_key = NULL;
30
31 if ((ctx = BN_CTX_new()) == NULL)
32 goto err;
d02b48c6 33
0f113f3e 34 if (dsa->priv_key == NULL) {
74924dcb 35 if ((priv_key = BN_secure_new()) == NULL)
0f113f3e
MC
36 goto err;
37 } else
38 priv_key = dsa->priv_key;
d02b48c6 39
0f113f3e 40 do
ddc6a5c8 41 if (!BN_priv_rand_range(priv_key, dsa->q))
0f113f3e
MC
42 goto err;
43 while (BN_is_zero(priv_key)) ;
d02b48c6 44
0f113f3e
MC
45 if (dsa->pub_key == NULL) {
46 if ((pub_key = BN_new()) == NULL)
47 goto err;
48 } else
49 pub_key = dsa->pub_key;
d02b48c6 50
0f113f3e 51 {
5584f65a 52 BIGNUM *prk = BN_new();
46a64376 53
5584f65a
MC
54 if (prk == NULL)
55 goto err;
56 BN_with_flags(prk, priv_key, BN_FLG_CONSTTIME);
d02b48c6 57
0f113f3e 58 if (!BN_mod_exp(pub_key, dsa->g, prk, dsa->p, ctx)) {
5584f65a 59 BN_free(prk);
0f113f3e
MC
60 goto err;
61 }
5584f65a
MC
62 /* We MUST free prk before any further use of priv_key */
63 BN_free(prk);
0f113f3e 64 }
d02b48c6 65
0f113f3e
MC
66 dsa->priv_key = priv_key;
67 dsa->pub_key = pub_key;
4889dadc 68 dsa->dirty_cnt++;
0f113f3e 69 ok = 1;
d02b48c6 70
0f113f3e 71 err:
23a1d5e9 72 if (pub_key != dsa->pub_key)
0f113f3e 73 BN_free(pub_key);
23a1d5e9 74 if (priv_key != dsa->priv_key)
0f113f3e 75 BN_free(priv_key);
23a1d5e9 76 BN_CTX_free(ctx);
26a7d938 77 return ok;
0f113f3e 78}