Path: blob/main/crypto/openssl/demos/pkey/EVP_PKEY_DSA_keygen.c
34907 views
/*-1* Copyright 2022-2024 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89/*10* Example showing how to generate an DSA key pair.11*/1213#include <openssl/evp.h>14#include "dsa.inc"1516/*17* Generate dsa params using default values.18* See the EVP_PKEY_DSA_param_fromdata demo if you need19* to load DSA params from raw values.20* See the EVP_PKEY_DSA_paramgen demo if you need to21* use non default parameters.22*/23static EVP_PKEY *dsa_genparams(OSSL_LIB_CTX *libctx, const char *propq)24{25EVP_PKEY *dsaparamkey = NULL;26EVP_PKEY_CTX *ctx = NULL;2728/* Use the dsa params in a EVP_PKEY ctx */29ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq);30if (ctx == NULL) {31fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n");32return NULL;33}3435if (EVP_PKEY_paramgen_init(ctx) <= 036|| EVP_PKEY_paramgen(ctx, &dsaparamkey) <= 0) {37fprintf(stderr, "DSA paramgen failed\n");38goto cleanup;39}40cleanup:41EVP_PKEY_CTX_free(ctx);42return dsaparamkey;43}4445int main(int argc, char **argv)46{47int ret = EXIT_FAILURE;48OSSL_LIB_CTX *libctx = NULL;49const char *propq = NULL;50EVP_PKEY *dsaparamskey = NULL;51EVP_PKEY *dsakey = NULL;52EVP_PKEY_CTX *ctx = NULL;5354/* Generate random dsa params */55dsaparamskey = dsa_genparams(libctx, propq);56if (dsaparamskey == NULL)57goto cleanup;5859/* Use the dsa params in a EVP_PKEY ctx */60ctx = EVP_PKEY_CTX_new_from_pkey(libctx, dsaparamskey, propq);61if (ctx == NULL) {62fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n");63goto cleanup;64}6566/* Generate a key using the dsa params */67if (EVP_PKEY_keygen_init(ctx) <= 068|| EVP_PKEY_keygen(ctx, &dsakey) <= 0) {69fprintf(stderr, "DSA keygen failed\n");70goto cleanup;71}7273if (!dsa_print_key(dsakey, 1, libctx, propq))74goto cleanup;7576ret = EXIT_SUCCESS;77cleanup:78EVP_PKEY_free(dsakey);79EVP_PKEY_free(dsaparamskey);80EVP_PKEY_CTX_free(ctx);81return ret;82}838485