xref: /freebsd/crypto/openssl/demos/pkey/EVP_PKEY_DSA_paramfromdata.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 /*-
2  * Copyright 2022 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  * Example showing how to load DSA params from raw data
12  * using EVP_PKEY_fromdata()
13  */
14 
15 #include <openssl/param_build.h>
16 #include <openssl/evp.h>
17 #include <openssl/core_names.h>
18 #include "dsa.inc"
19 
20 int main(int argc, char **argv)
21 {
22     int rv = EXIT_FAILURE;
23     OSSL_LIB_CTX *libctx = NULL;
24     const char *propq = NULL;
25     EVP_PKEY_CTX *ctx = NULL;
26     EVP_PKEY *dsaparamkey = NULL;
27     OSSL_PARAM_BLD *bld = NULL;
28     OSSL_PARAM *params = NULL;
29     BIGNUM *p = NULL, *q = NULL, *g = NULL;
30 
31     p = BN_bin2bn(dsa_p, sizeof(dsa_p), NULL);
32     q = BN_bin2bn(dsa_q, sizeof(dsa_q), NULL);
33     g = BN_bin2bn(dsa_g, sizeof(dsa_g), NULL);
34     if (p == NULL || q == NULL || g == NULL)
35         goto cleanup;
36 
37     /* Use OSSL_PARAM_BLD if you need to handle BIGNUM Parameters */
38     bld = OSSL_PARAM_BLD_new();
39     if (bld == NULL)
40         goto cleanup;
41     if (!OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p)
42             || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q)
43             || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g))
44         goto cleanup;
45     params = OSSL_PARAM_BLD_to_param(bld);
46     if (params == NULL)
47         goto cleanup;
48 
49     ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq);
50     if (ctx == NULL) {
51         fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n");
52         goto cleanup;
53     }
54 
55     if (EVP_PKEY_fromdata_init(ctx) <= 0
56             || EVP_PKEY_fromdata(ctx, &dsaparamkey, EVP_PKEY_KEY_PARAMETERS, params) <= 0) {
57         fprintf(stderr, "EVP_PKEY_fromdata() failed\n");
58         goto cleanup;
59     }
60 
61     if (!dsa_print_key(dsaparamkey, 0, libctx, propq))
62         goto cleanup;
63 
64     rv = EXIT_SUCCESS;
65 cleanup:
66     EVP_PKEY_free(dsaparamkey);
67     EVP_PKEY_CTX_free(ctx);
68     OSSL_PARAM_free(params);
69     OSSL_PARAM_BLD_free(bld);
70     BN_free(g);
71     BN_free(q);
72     BN_free(p);
73 
74     return rv;
75 }
76