I want to know how to generate RSA private key using OpenSSL library in my C source file. I know how to generate it using terminal command.
Actually my server.c file will generate a private key and send to client.c Please help me with some source code if possible, otherwise any help will be appreciated.
I'm working on Linux machine.
You would use
RSA_generate_key_ex
, after properly seeding the PRNG usingRAND_add
Generating the key is easy. Just use
RSA_generate_key_ex
. The program below shows you how to do it.Saving the public and private key is a different matter because you need to know the format. The program below shows you how to do it in a number of formats.
Here are the various functions and formats.
Related, see What is the differences between “BEGIN RSA PRIVATE KEY” and “BEGIN PRIVATE KEY”. It dicusses the difference between SubjectPublicKeyInfo, PrivateKeyInfo, and the public and private keys.
PEM_write_bio_RSAPublicKey (PKCS PEM format). Notice
BEGIN RSA PUBLIC KEY
:PEM_write_bio_PUBKEY (Traditional PEM format). Notice
BEGIN PUBLIC KEY
:PEM_write_bio_PrivateKey (PEM). Notice
BEGIN PRIVATE KEY
:PEM_write_bio_PKCS8PrivateKey (PEM). Notice
BEGIN PRIVATE KEY
:PEM_write_bio_RSAPrivateKey (PEM). Notice
BEGIN RSA PRIVATE KEY
:i2d_RSAPublicKey_bio (ASN.1/DER):
i2d_RSAPrivateKey_bio (ASN.1/DER):
The program is written in C++, even though you have a C tag. It allows us to avoid a lot of error checking and cleanup because its automatic. And its easy enough to convert back to C.
kExp=3 can be a security hole, please use 65537 instead. The problem is called "Small RSA Exponent" ,see e.g. http://en.wikipedia.org/wiki/Coppersmith%27s_Attack and http://www.usna.edu/Users/math/wdj/book/node45.html Also please use more than 1024 bits.