DEV Community

Cover image for Generate RSA Keypair Using OpenSSL
ABHIRAM P JAYAN
ABHIRAM P JAYAN

Posted on

Generate RSA Keypair Using OpenSSL

OpenSSL is a robust, commercial-grade, and full-featured toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. It is also a general-purpose cryptography library. OpenSSL is licensed under an Apache-style license, which basically means that you are free to get and use it for commercial and non-commercial purposes subject to some simple license conditions. OpenSSL can generate several kinds of public/private keypairs. RSA is the most common kind of keypair generation.
Security Image

Generate an RSA keypair with a 2048 bit private key

Execute command: openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048 (previously openssl genrsa -out private_key.pem 2048)

openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
Enter fullscreen mode Exit fullscreen mode

Make sure to prevent other users from reading your key by executing chmod go-r private_key.pem afterward.

Extracting the public key from an RSA keypair

Execute command: openssl rsa -pubout -in private_key.pem -out public_key.pem

openssl rsa -pubout -in private_key.pem -out public_key.pem
Enter fullscreen mode Exit fullscreen mode

A new file is created, public_key.pem, with the public key.

OpenSSL Commands to Convert SSL Certificates on Your Machine

It is highly recommended that you convert to and from .pfx files on your own machine using OpenSSL so you can keep the private key there. Use the following OpenSSL commands to convert SSL certificate to different formats on your own machine:

OpenSSL Convert PEM

Convert PEM to DER

openssl x509 -outform der -in certificate.pem -out certificate.der
Enter fullscreen mode Exit fullscreen mode

Convert PEM to P7B

openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer
Enter fullscreen mode Exit fullscreen mode

Convert PEM to PFX

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
Enter fullscreen mode Exit fullscreen mode

OpenSSL Convert DER

Convert DER to PEM

openssl x509 -inform der -in certificate.cer -out certificate.pem
Enter fullscreen mode Exit fullscreen mode

OpenSSL Convert P7B

Convert P7B to PEM

openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
Enter fullscreen mode Exit fullscreen mode

Convert P7B to PFX

openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer
Enter fullscreen mode Exit fullscreen mode

OpenSSL Convert PFX

Convert PFX to PEM

openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
Enter fullscreen mode Exit fullscreen mode

Discussion (0)