EVP: Implement support for key downgrading in backends
[openssl.git] / crypto / dsa / dsa_backend.c
1 /*
2  * Copyright 2020 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 #include <openssl/core_names.h>
11 #include "crypto/dsa.h"
12
13 /*
14  * The intention with the "backend" source file is to offer backend support
15  * for legacy backends (EVP_PKEY_ASN1_METHOD and EVP_PKEY_METHOD) and provider
16  * implementations alike.
17  */
18
19 int dsa_key_fromdata(DSA *dsa, const OSSL_PARAM params[])
20 {
21     const OSSL_PARAM *param_priv_key, *param_pub_key;
22     BIGNUM *priv_key = NULL, *pub_key = NULL;
23
24     if (dsa == NULL)
25         return 0;
26
27     param_priv_key =
28         OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY);
29     param_pub_key =
30         OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY);
31
32     /* It's ok if neither half is present */
33     if (param_priv_key == NULL && param_pub_key == NULL)
34         return 1;
35
36     /*
37      * DH documentation says that a public key must be present if a
38      * private key is present.
39      */
40     if (param_priv_key != NULL && param_pub_key == NULL)
41         return 0;
42
43     if (param_pub_key != NULL && !OSSL_PARAM_get_BN(param_pub_key, &pub_key))
44         goto err;
45     if (param_priv_key != NULL && !OSSL_PARAM_get_BN(param_priv_key, &priv_key))
46         goto err;
47
48     if (!DSA_set0_key(dsa, pub_key, priv_key))
49         goto err;
50
51     return 1;
52
53  err:
54     BN_clear_free(priv_key);
55     BN_free(pub_key);
56     return 0;
57 }