2 rsagen.c -- RSA key generation and export
3 Copyright (C) 2008-2022 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "../system.h"
22 #include <openssl/pem.h>
23 #include <openssl/err.h>
25 #define TINC_RSA_INTERNAL
27 #if OPENSSL_VERSION_MAJOR < 3
30 typedef EVP_PKEY rsa_t;
31 #include <openssl/encoder.h>
32 #include <openssl/evp.h>
35 #include "../logger.h"
36 #include "../rsagen.h"
39 #if OPENSSL_VERSION_MAJOR < 3
40 /* This function prettyprints the key generation process */
42 static int indicator(int a, int b, BN_GENCB *cb) {
61 fprintf(stderr, " p\n");
65 fprintf(stderr, " q\n");
84 rsa_t *rsa_generate(size_t bits, unsigned long exponent) {
85 BIGNUM *bn_e = BN_new();
92 BN_set_word(bn_e, exponent);
94 #if OPENSSL_VERSION_MAJOR < 3
96 BN_GENCB *cb = BN_GENCB_new();
102 BN_GENCB_set(cb, indicator, NULL);
104 int result = RSA_generate_key_ex(rsa, (int) bits, bn_e, cb);
109 fprintf(stderr, "Error during key generation!\n");
115 EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
118 && EVP_PKEY_keygen_init(ctx) > 0
119 && EVP_PKEY_CTX_set1_rsa_keygen_pubexp(ctx, bn_e) > 0
120 && EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, (int)bits) > 0
121 && EVP_PKEY_keygen(ctx, &rsa) > 0;
124 EVP_PKEY_CTX_free(ctx);
128 openssl_err("generate key");
139 // Write PEM RSA keys
141 #if OPENSSL_VERSION_MAJOR >= 3
142 static bool write_key_to_pem(const rsa_t *rsa, FILE *fp, int selection) {
143 OSSL_ENCODER_CTX *enc = OSSL_ENCODER_CTX_new_for_pkey(rsa, selection, "PEM", NULL, NULL);
146 openssl_err("create encoder context");
150 bool ok = OSSL_ENCODER_to_fp(enc, fp);
151 OSSL_ENCODER_CTX_free(enc);
154 openssl_err("write key to file");
161 bool rsa_write_pem_public_key(rsa_t *rsa, FILE *fp) {
162 #if OPENSSL_VERSION_MAJOR < 3
163 return PEM_write_RSAPublicKey(fp, rsa);
165 return write_key_to_pem(rsa, fp, OSSL_KEYMGMT_SELECT_PUBLIC_KEY);
169 bool rsa_write_pem_private_key(rsa_t *rsa, FILE *fp) {
170 #if OPENSSL_VERSION_MAJOR < 3
171 return PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL);
173 return write_key_to_pem(rsa, fp, OSSL_KEYMGMT_SELECT_PRIVATE_KEY);