How to Use OpenSSL to Generate RSA Keys in C/C++

It is known that RSA is a cryptosystem which is used for the security of data transmission. This tutorial introduces how to use RSA to generate a pair of public and private keys on Windows.

  1. Download and install OpenSSL https://www.openssl.org/community/binaries.html.
  2. Find libeay32.lib, ssleay32.lib and libeay32.dll.
  3. The following sample code will generate a public key “public.pem” and a private key “private.pem”.
#include <stdio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>

bool generate_key()
{
	int				ret = 0;
	RSA				*r = NULL;
	BIGNUM			*bne = NULL;
	BIO				*bp_public = NULL, *bp_private = NULL;

	int				bits = 2048;
	unsigned long	e = RSA_F4;

	// 1. generate rsa key
	bne = BN_new();
	ret = BN_set_word(bne,e);
	if(ret != 1){
		goto free_all;
	}

	r = RSA_new();
	ret = RSA_generate_key_ex(r, bits, bne, NULL);
	if(ret != 1){
		goto free_all;
	}

	// 2. save public key
	bp_public = BIO_new_file("public.pem", "w+");
	ret = PEM_write_bio_RSAPublicKey(bp_public, r);
	if(ret != 1){
		goto free_all;
	}

	// 3. save private key
	bp_private = BIO_new_file("private.pem", "w+");
	ret = PEM_write_bio_RSAPrivateKey(bp_private, r, NULL, NULL, 0, NULL, NULL);

	// 4. free
free_all:

	BIO_free_all(bp_public);
	BIO_free_all(bp_private);
	RSA_free(r);
	BN_free(bne);

	return (ret == 1);
}

int main(int argc, char* argv[]) 
{
	generate_key();
        return 0;
}

You can feel free to download the sample code, and run it in Visual Studio.

  • Nico Elk

    hi there, I know it s an old thread but.. having the same kind of error when trying to get a RSA* with PEM_read_bio_RSA_PUBKEY

    ERROR: Could not load PUBLIC KEY! PEM_read_bio_RSA_PUBKEY FAILED: error:0906D06C:lib(9):func(109):reason(108)

    anyone know how to read the generated pem file again for latter use ?

    Thanks!

  • NameIst Unbekannt

    Const in C? Tell me more!
    “and where is random generator seeding?” => Maybe in OpenSSL itself?
    Laughing my ass off haha..

  • Taras Yosypenko

    great code??!!! oO, what do GOTOs do there? are u kiddin? and does the author know the keyword CONST?

  • http://www.dynamsoft.com Desmond Shaw

    It’s padding error. Check your publicKeyStr.

  • Buck Hsieh

    great code.
    I tried to use this key generator for RSA encryption/decryption.
    After I generate public.pem and try to get public key from it. The code complain about:

    ERROR: Could not load PUBLIC KEY! PEM_read_bio_RSA_PUBKEY FAILED: error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed

    The following is the code:

    RSA* rsa_loadPUBLICKeyFromString( const char* publicKeyStr )
    {
    BIO* bio = BIO_new_mem_buf( (void*)publicKeyStr, -1 ) ; // -1: assume string is null terminated

    BIO_set_flags( bio, BIO_FLAGS_BASE64_NO_NL ) ; // NO NL

    // Load the RSA key from the BIO
    RSA* rsaPubKey = PEM_read_bio_RSA_PUBKEY( bio, NULL, NULL, NULL ) ;
    if( !rsaPubKey )
    printf( “ERROR: Could not load PUBLIC KEY! PEM_read_bio_RSA_PUBKEY FAILED: %sn”, ERR_error_string( ERR_get_error(), NULL ) ) ;

    BIO_free( bio ) ;
    return rsaPubKey ;
    }

    Could you please give me a hint?