OpenSSL includes tonnes of features covering a broad range of use cases, and it’s difficult to remember its syntax for all of them and quite easy to get lost. We will share how to use OpenSSL RSA to create public and private keys in this post.
Understanding Public Key and Private Key
- The public key is published for all the world to see. Public keys are created using a complex asymmetric algorithm to pair them with an associated private key.
- The private key is a secret key known only by its owner, with the private key and public key paired such that the recipient can use the corresponding key to decrypt the cipher text and read the original message. Private keys are generated using the same algorithms that create public keys to create strong keys that are bonded mathematically.
Generate a 2048 bit RSA Private Key
The key size or bit length of public keys determines the strength of protection. For example, 2048-bit RSA keys are often employed in SSL certificates, digital signatures, and other digital certificates. This key length offers sufficient cryptographic security to keep hackers from cracking the algorithm.
openssl genrsa -out private-key.pem 2048
In this example, we have used a key length of 2048 bits.
This gives us a PEM file containing our RSA private key, which should look something like the following:
—–BEGIN RSA PRIVATE KEY—–
—–END RSA PRIVATE KEY—–
Generate corresponding Public key
openssl rsa -in private-key.pem -pubout -out public-key.pem
This should give us another PEM file, containing the public key.
The PEM public key format uses the header and footer lines:
—–BEGIN PUBLIC KEY—–
—–END PUBLIC KEY—–
Generate a private RSA key with a password
openssl genrsa -des3 -out private.pem 2048
That generates a 2048-bit RSA key , encrypts them with a password we provide and writes them to a file.
Create an RSA Self-Signed Certificate Using OpenSSL
Now that we have a private key, we can use it to generate a self-signed certificate. This is not required, but it allows us to use the key for server/client authentication, or gain X509 specific functionality in technologies
openssl req -new -x509 -key private-key.pem -out cert.pem -days 360
OpenSSL RSA Cheat Sheet
To remove the pass phrase on an RSA private key:
openssl rsa -in key.pem -out keyout.pem
To encrypt a private key using triple DES:
openssl rsa -in key.pem -des3 -out keyout.pem
To convert a private key from PEM to DER format:
openssl rsa -in key.pem -outform DER -out keyout.der
To print out the components of a private key to standard output:
openssl rsa -in key.pem -text -noout
To just output the public part of a private key:
openssl rsa -in key.pem -pubout -out pubkey.pem
Output the public part of a private key in RSAPublicKey format:
openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem