EVP_PKEY_DSA_keygen.c 2.2 KB

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