Path: blob/main/crypto/openssl/demos/pkey/EVP_PKEY_RSA_keygen.c
34907 views
/*-1* Copyright 2022-2023 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 RSA key pair.11*12* When generating an RSA key, you must specify the number of bits in the key. A13* reasonable value would be 4096. Avoid using values below 2048. These values14* are reasonable as of 2022.15*/1617#include <string.h>18#include <stdio.h>19#include <openssl/err.h>20#include <openssl/evp.h>21#include <openssl/rsa.h>22#include <openssl/core_names.h>23#include <openssl/pem.h>2425/* A property query used for selecting algorithm implementations. */26static const char *propq = NULL;2728/*29* Generates an RSA public-private key pair and returns it.30* The number of bits is specified by the bits argument.31*32* This uses the long way of generating an RSA key.33*/34static EVP_PKEY *generate_rsa_key_long(OSSL_LIB_CTX *libctx, unsigned int bits)35{36EVP_PKEY_CTX *genctx = NULL;37EVP_PKEY *pkey = NULL;38unsigned int primes = 2;3940/* Create context using RSA algorithm. "RSA-PSS" could also be used here. */41genctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", propq);42if (genctx == NULL) {43fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n");44goto cleanup;45}4647/* Initialize context for key generation purposes. */48if (EVP_PKEY_keygen_init(genctx) <= 0) {49fprintf(stderr, "EVP_PKEY_keygen_init() failed\n");50goto cleanup;51}5253/*54* Here we set the number of bits to use in the RSA key.55* See comment at top of file for information on appropriate values.56*/57if (EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, bits) <= 0) {58fprintf(stderr, "EVP_PKEY_CTX_set_rsa_keygen_bits() failed\n");59goto cleanup;60}6162/*63* It is possible to create an RSA key using more than two primes.64* Do not do this unless you know why you need this.65* You ordinarily do not need to specify this, as the default is two.66*67* Both of these parameters can also be set via EVP_PKEY_CTX_set_params, but68* these functions provide a more concise way to do so.69*/70if (EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) <= 0) {71fprintf(stderr, "EVP_PKEY_CTX_set_rsa_keygen_primes() failed\n");72goto cleanup;73}7475/*76* Generating an RSA key with a number of bits large enough to be secure for77* modern applications can take a fairly substantial amount of time (e.g.78* one second). If you require fast key generation, consider using an EC key79* instead.80*81* If you require progress information during the key generation process,82* you can set a progress callback using EVP_PKEY_set_cb; see the example in83* EVP_PKEY_generate(3).84*/85fprintf(stdout, "Generating RSA key, this may take some time...\n");86if (EVP_PKEY_generate(genctx, &pkey) <= 0) {87fprintf(stderr, "EVP_PKEY_generate() failed\n");88goto cleanup;89}9091/* pkey is now set to an object representing the generated key pair. */9293cleanup:94EVP_PKEY_CTX_free(genctx);95return pkey;96}9798/*99* Generates an RSA public-private key pair and returns it.100* The number of bits is specified by the bits argument.101*102* This uses a more concise way of generating an RSA key, which is suitable for103* simple cases. It is used if -s is passed on the command line, otherwise the104* long method above is used. The ability to choose between these two methods is105* shown here only for demonstration; the results are equivalent.106*/107static EVP_PKEY *generate_rsa_key_short(OSSL_LIB_CTX *libctx, unsigned int bits)108{109EVP_PKEY *pkey = NULL;110111fprintf(stdout, "Generating RSA key, this may take some time...\n");112pkey = EVP_PKEY_Q_keygen(libctx, propq, "RSA", (size_t)bits);113114if (pkey == NULL)115fprintf(stderr, "EVP_PKEY_Q_keygen() failed\n");116117return pkey;118}119120/*121* Prints information on an EVP_PKEY object representing an RSA key pair.122*/123static int dump_key(const EVP_PKEY *pkey)124{125int ret = 0;126int bits = 0;127BIGNUM *n = NULL, *e = NULL, *d = NULL, *p = NULL, *q = NULL;128129/*130* Retrieve value of n. This value is not secret and forms part of the131* public key.132*133* Calling EVP_PKEY_get_bn_param with a NULL BIGNUM pointer causes134* a new BIGNUM to be allocated, so these must be freed subsequently.135*/136if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_N, &n) == 0) {137fprintf(stderr, "Failed to retrieve n\n");138goto cleanup;139}140141/*142* Retrieve value of e. This value is not secret and forms part of the143* public key. It is typically 65537 and need not be changed.144*/145if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_E, &e) == 0) {146fprintf(stderr, "Failed to retrieve e\n");147goto cleanup;148}149150/*151* Retrieve value of d. This value is secret and forms part of the private152* key. It must not be published.153*/154if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_D, &d) == 0) {155fprintf(stderr, "Failed to retrieve d\n");156goto cleanup;157}158159/*160* Retrieve value of the first prime factor, commonly known as p. This value161* is secret and forms part of the private key. It must not be published.162*/163if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_FACTOR1, &p) == 0) {164fprintf(stderr, "Failed to retrieve p\n");165goto cleanup;166}167168/*169* Retrieve value of the second prime factor, commonly known as q. This value170* is secret and forms part of the private key. It must not be published.171*172* If you are creating an RSA key with more than two primes for special173* applications, you can retrieve these primes with174* OSSL_PKEY_PARAM_RSA_FACTOR3, etc.175*/176if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_FACTOR2, &q) == 0) {177fprintf(stderr, "Failed to retrieve q\n");178goto cleanup;179}180181/*182* We can also retrieve the key size in bits for informational purposes.183*/184if (EVP_PKEY_get_int_param(pkey, OSSL_PKEY_PARAM_BITS, &bits) == 0) {185fprintf(stderr, "Failed to retrieve bits\n");186goto cleanup;187}188189/* Output hexadecimal representations of the BIGNUM objects. */190fprintf(stdout, "\nNumber of bits: %d\n\n", bits);191fprintf(stdout, "Public values:\n");192fprintf(stdout, " n = 0x");193BN_print_fp(stdout, n);194fprintf(stdout, "\n");195196fprintf(stdout, " e = 0x");197BN_print_fp(stdout, e);198fprintf(stdout, "\n\n");199200fprintf(stdout, "Private values:\n");201fprintf(stdout, " d = 0x");202BN_print_fp(stdout, d);203fprintf(stdout, "\n");204205fprintf(stdout, " p = 0x");206BN_print_fp(stdout, p);207fprintf(stdout, "\n");208209fprintf(stdout, " q = 0x");210BN_print_fp(stdout, q);211fprintf(stdout, "\n\n");212213/* Output a PEM encoding of the public key. */214if (PEM_write_PUBKEY(stdout, pkey) == 0) {215fprintf(stderr, "Failed to output PEM-encoded public key\n");216goto cleanup;217}218219/*220* Output a PEM encoding of the private key. Please note that this output is221* not encrypted. You may wish to use the arguments to specify encryption of222* the key if you are storing it on disk. See PEM_write_PrivateKey(3).223*/224if (PEM_write_PrivateKey(stdout, pkey, NULL, NULL, 0, NULL, NULL) == 0) {225fprintf(stderr, "Failed to output PEM-encoded private key\n");226goto cleanup;227}228229ret = 1;230cleanup:231BN_free(n); /* not secret */232BN_free(e); /* not secret */233BN_clear_free(d); /* secret - scrub before freeing */234BN_clear_free(p); /* secret - scrub before freeing */235BN_clear_free(q); /* secret - scrub before freeing */236return ret;237}238239int main(int argc, char **argv)240{241int ret = EXIT_FAILURE;242OSSL_LIB_CTX *libctx = NULL;243EVP_PKEY *pkey = NULL;244unsigned int bits = 4096;245int bits_i, use_short = 0;246247/* usage: [-s] [<bits>] */248if (argc > 1 && strcmp(argv[1], "-s") == 0) {249--argc;250++argv;251use_short = 1;252}253254if (argc > 1) {255bits_i = atoi(argv[1]);256if (bits < 512) {257fprintf(stderr, "Invalid RSA key size\n");258return EXIT_FAILURE;259}260261bits = (unsigned int)bits_i;262}263264/* Avoid using key sizes less than 2048 bits; see comment at top of file. */265if (bits < 2048)266fprintf(stderr, "Warning: very weak key size\n\n");267268/* Generate RSA key. */269if (use_short)270pkey = generate_rsa_key_short(libctx, bits);271else272pkey = generate_rsa_key_long(libctx, bits);273274if (pkey == NULL)275goto cleanup;276277/* Dump the integers comprising the key. */278if (dump_key(pkey) == 0) {279fprintf(stderr, "Failed to dump key\n");280goto cleanup;281}282283ret = EXIT_SUCCESS;284cleanup:285EVP_PKEY_free(pkey);286OSSL_LIB_CTX_free(libctx);287return ret;288}289290291