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 generate an DSA key pair.
12 */
13
14#include <openssl/evp.h>
15#include "dsa.inc"
16
17/*
18 * Generate dsa params using default values.
19 * See the EVP_PKEY_DSA_param_fromdata demo if you need
20 * to load DSA params from raw values.
21 * See the EVP_PKEY_DSA_paramgen demo if you need to
22 * use non default parameters.
23 */
24EVP_PKEY *dsa_genparams(OSSL_LIB_CTX *libctx, const char *propq)
25{
26    EVP_PKEY *dsaparamkey = NULL;
27    EVP_PKEY_CTX *ctx = NULL;
28
29    /* Use the dsa params in a EVP_PKEY ctx */
30    ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq);
31    if (ctx == NULL) {
32        fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n");
33        return NULL;
34    }
35
36    if (EVP_PKEY_paramgen_init(ctx) <= 0
37            || EVP_PKEY_paramgen(ctx, &dsaparamkey) <= 0) {
38        fprintf(stderr, "DSA paramgen failed\n");
39        goto cleanup;
40    }
41cleanup:
42    EVP_PKEY_CTX_free(ctx);
43    return dsaparamkey;
44}
45
46int main(int argc, char **argv)
47{
48    int rv = EXIT_FAILURE;
49    OSSL_LIB_CTX *libctx = NULL;
50    const char *propq = NULL;
51    EVP_PKEY *dsaparamskey = NULL;
52    EVP_PKEY *dsakey = NULL;
53    EVP_PKEY_CTX *ctx = NULL;
54
55    /* Generate random dsa params */
56    dsaparamskey = dsa_genparams(libctx, propq);
57    if (dsaparamskey == NULL)
58        goto cleanup;
59
60    /* Use the dsa params in a EVP_PKEY ctx */
61    ctx = EVP_PKEY_CTX_new_from_pkey(libctx, dsaparamskey, propq);
62    if (ctx == NULL) {
63        fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n");
64        goto cleanup;
65    }
66
67    /* Generate a key using the dsa params */
68    if (EVP_PKEY_keygen_init(ctx) <= 0
69            || EVP_PKEY_keygen(ctx, &dsakey) <= 0) {
70        fprintf(stderr, "DSA keygen failed\n");
71        goto cleanup;
72    }
73
74    if (!dsa_print_key(dsakey, 1, libctx, propq))
75        goto cleanup;
76
77    rv = EXIT_SUCCESS;
78cleanup:
79    EVP_PKEY_free(dsakey);
80    EVP_PKEY_free(dsaparamskey);
81    EVP_PKEY_CTX_free(ctx);
82    return rv;
83}
84