Encrypt and Decrypt data using RSA with Openssl

What is RSA?

What is OpenSSL?

Generate private key:

  • openssl genrsa -out privatekey.pem 2048
  • openssl genrsa  // private key is written to stdout

Generate public key from the private key generated above:

  • openssl rsa -pubout -in privatekey.pem -out publickey.pem
  • openssl rsa -pubout  // copy paste the private key from the stdout; public key will be displayed on the screen

You must have your public and private keys in two files to continue. I have my public key in publickey.pem and private key in privatekey.pem and data to be encrypted in data.txt. Lets now encrypt and decrypt to check the correctness.

  • openssl rsautl -in data.txt -out encrypted_data.txt -inkey publickey.pem -encrypt -pubin

You will have encrypted_data.txt file created and you will see some wierd characters if you open it. Don’t worry, that is the exact purpose of encryption: make it not readable unless you decrypt with private key. So now lets use our private key to decrypt. Lets see if we get our original data back.

  • openssl rsautl -in encrypted_data.txt -out decrypted_data.txt  -inkey publickey.pem -encrypt -pubin

Compare data.txt and decrypted_data.txt and see the magic.. 😛

Published by


A strong believer of: 1. Knowledge is power 2. Progress comes from proper application of knowledge 3. Reverent attains wisdom 4. For one's own salvation, and for the welfare of the world

One thought on “Encrypt and Decrypt data using RSA with Openssl”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s