Each private key has a corresponding public key. Generally, the public key can be easily derived from the private key, but deriving the private key from the public key is computationally infeasible.
- In a public-key cryptosystem, a public key is a key that can be used for verifying digital signatures generated using a corresponding private key. In some cryptosystems, public keys can also be used for encrypting messages so that they can only be decrypted using the corresponding private key.
- In public-key cryptosystems, a private key is a key used for digitally signing documents. In some cryptosystems, it can also be used for decrypting data encrypted using a public key.
We will review how encryption works with public key and private key in the following example.
create RSA private key with openssl command
This command generates a PEM-encoded private key and stores it in the file rsaprivkey.pem. This example creates a 2048-bit key, which should work for nearly any purpose. The resulting private key should be kept secret and is used to sign and decrypt data.
- openssl genrsa -out rsaprivkey.pem 2048
Extract public key from private key
Extract the public key from the private key, which can be used below:
- openssl rsa -in rsaprivkey.pem -outform PEM -pubout -out public.pem
Encrypt test.txt file content using public key
Create a new file called test.txt file with content “message test”. Perform the following command to create encrypted message to cipher.txt file.
- openssl rsautl -encrypt -in test.txt -pubin -inkey public.pem -out cipher.txt
Decrypt from cipher.txt using private key
Perform following command to decrypt cipher.txt content.
- openssl rsautl -decrypt -in cipher.txt -inkey rsaprivkey.pem
Confirm that we are able to decrypt our cipher.txt file content to our terminal.
Make sure that output from terminal is matching the content on test.txt file.
If the content does not match, then private key has been manipulated and may not work with our public key. Consider creating a new private key.