How to do Asymmetric Encryption and Decryption

In cryptography, Encryption is the conversion of data into a form, called a ciphertext, that cannot be easily understood by unauthorized people. Decryption is the process of converting encrypted data back into its original form, so it can be understood. There are many ways for encryption, In following article, I have explained only two methods Symmetric and Asymmetric encryption.


Openssl based Asymmetric Encryption and Decryption :

# First we need to genrate private key

[ root @ leolinux ~]#  openssl genrsa  -out  private.key  1024


 ## Encrypted private key e.g. password protected

[ root @ leolinux ~]#  openssl genrsa  -des3  -out  private.key  1024 

# Generate Public key 

[ root @ leolinux ~]#  openssl   rsa  -in  private.key   -out  public.key  -pubout

# To encrypt a file run following command

[ root @ leolinux ~]#  openssl  rsautl  -encrypt  -in  plain.txt  -out  cipher.txt  -inkey  public.key   -pubin

# To decrypt a file

[ root @ leolinux ~]#  openssl  rsutl  -decrypt  -n  cipher.txt  -out  plain.txt  -inkey  private.key


GPG based Asymmetric Encryption and Decryption :

# First we need to generate private and public key pair.

[ root @ leolinux ~]#  gpg  --gen-key 

( fill all information and set passphrase )

# To encrypt file run following command.

[ root @ leolinux ~]#  gpg  --armor  --recipient   --encrypt  plain.txt

# To encrypt file and add signature. 

[ root @ leolinux ~]#  gpg  --armor  --recipient  --sign  --encrypt  plain.txt

# To decrypt file.

[ root @ leolinux ~]#  gpg  --out plain.txt  --decrypt  cipher.txt

# To list private key.

[ root @ leolinux ~]#  gpg  --list-secret-key 

# To list public keys.

[ root @ leolinux ~]#  gpg  --list-key 

# To export public key.

[ root @ leolinux ~]#  gpg  --armor  --export --out  public.key

# To import public key.

[ root @ leolinux ~]#  gpg  --import  public.key