How to Encrypt and Decrypt files/folders in Linux using GnuPG

Updated on September 3, 2017

Recently one of our reader had a question : “How to encrypt and decrypt few files/folders in Linux preferably CLI based?”

Here is the solution: To encrypt and decrypt files we shall use GnuPG (GNU Privacy Guard), which is GNU’s tool for encryption and signing. GnuPG is a GPL Licensed implementation of OpenPGP ( Pretty Good Privacy ) standard as defined in RFC 4880. GnuPG itself is a commandline tool without any graphical stuff. It is the real crypto engine which can be used directly from a command prompt, from shell scripts or by other programs. Therefore it can be considered as a backend for other applications.

Advantages of GnuPG:

  • Better functionality than PGP and some security enhancements over PGP 2.
  • Decrypts and verifies PGP 5, 6 and 7 messages.
  • Supports ElGamal, DSA, RSA, AES, 3DES, Blowfish, Twofish, CAST5, MD5, SHA-1, RIPE-MD-160 and TIGER.
  • Easy implementation of new algorithms using extension modules.
  • Supports key and signature expiration dates.
  • English, Danish, Dutch, Esperanto, Estonian, French, German, Japanese, Italian, Polish, Portuguese (Brazilian), Portuguese (Portuguese), Russian, Spanish, Swedish and Turkish language support.

In this article we shall see GnuPG installation, encryption and decryption of files using password as well as key pair.

Encrypt and Decrypt files on Linux
Encrypt and Decrypt files on Linux

How to Install GnuPG

GnuPG would be installed on most of the Linux distros. To verify run the below command:

[root@catest]# yum info gnupg

If it already finds the installation, then you no need to install, else install using yum (Know how to configure Yum).

[root@catest]#yum install gnupg

How to Encrypt a file in Linux using password – GnuPG

Follow the below command to encrypt a file using a passphrase:

[root@catest]# gpg -c <filename>

Running above command for the first time would create .gnupg directory in your home directory. Under .gnupg directory two files would be created : gpg.conf, pubring.gpg & secring.gpg. gpg.conf is the default configuration file gpg would consider in encryption and decryption of the files, pubring.gpg is the public keyring and secring.gpg is the secret keyring.

Here -c option would make gpg to encrypt the file with a symmetric cipher using a passphrase. The default symmetric cipher used is CAST5, but others may be chosen with the –cipher-algo option.

To encrypt a file called sample.txt run the below command :

[root@catest]# gpg -c sample.txt
Enter passphrase:<YOUR-SECRET-PASSWORD>
Repeat passphrase:<YOUR-SECRET-PASSWORD>

The above command would prompt for passphrase twice to confirm and on success it would create sample.txt.gpg retaining original sample.txt file too. It is advisable to delete the original file sample.txt and have only the encrypted file.

Note: if you ever forget your passphrase, it would be impossible to decrypt the file!

How to Decrypt a file in Linux using password – GnuPG

To decrypt an already encrypted file use the below command:

[root@catest ~]# gpg sample.txt.gpg
gpg: CAST5 encrypted data
Enter passphrase:

Running above command would prompt for the passphrase to decrypt the file. Upon success, the encrypted file would be decrypted.

How to generate public-private key pair – GnuPG

Before starting of encryption using key pair, first of all a GPG private/public key-pair should be created using the below command:

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

Follow the instructions. The defaults should be sufficient for a first test. Something like the below will appear:

gpg (GnuPG) 1.4.5; Copyright (C) 2006 Free Software Foundation, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the file COPYING for details.

gpg: directory `/home/ramyasanthosh/.gnupg' created
gpg: new configuration file `/home/ramyasanthosh/.gnupg/gpg.conf' created
gpg: WARNING: options in `/home/ramyasanthosh/.gnupg/gpg.conf' are not yet active during this run
gpg: keyring `/home/ramyasanthosh/.gnupg/secring.gpg' created
gpg: keyring `/home/ramyasanthosh/.gnupg/pubring.gpg' created
Please select what kind of key you want:
(1) DSA and Elgamal (default)
(2) DSA (sign only)
(5) RSA (sign only)
Your selection? 1
DSA keypair will have 1024 bits.
ELG-E keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
<n> = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>y = key expires in n years
Key is valid for? (0) 7
Key expires at Mon 30 Dec 2013 04:46:14 PM IST
Is this correct? (y/N) y

You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"

Real name: ramyasanthosh
Email address: techglimpse.newsletter@gmail.com
Comment: Testing
You selected this USER-ID:
"ramyasanthosh (Testing) <techglimpse.newsletter@gmail.com>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o
You need a Passphrase to protect your secret key.

Enter passphrase:
Repeat passphrase:

You will be asked for a passphrase to the key. It’s highly recommended to use a strong one. It is not needed for encryption of files anyway, but is required during the decryption of files.

We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
.++++++++++....++++++++++.++++++++++++++++++++..+++++.+++++++++++++++++++++++++++++++++++..+++++.++++++++++++++++++++..+++++++++++++++..++++++++++>+++++.+++++......>+++++..+++++

Not enough random bytes available. Please do some other work to give
the OS a chance to collect more entropy! (Need 284 more bytes)

Once sufficient random bytes is available, the keys will be generated. But making available sufficient random bytes is not quite an easy task. so the solution is:

Solution to “Not enough random bytes available – GnuPG”

We all know it’s quite a pain to create entropy manually for a GPG key creation. So using rngd we shall feed random data from hardware device to kernel random device as shown below:

[root@catest .gnupg]# ls -l /dev/urandom
cr--r--r-- 1 root root 1, 9 Oct 11 11:14 /dev/urandom
[root@catest .gnupg]# which rngd
/sbin/rngd
[root@catest .gnupg]# rngd -r /dev/random

Then create your GPG key and the keys will be generated as as shown below:

++++++++++.++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++.+++++.+++++++++++++++.+++++..+++++.+++++++++++++++.+++++++++++++++>+++++..+++++.+++++^^^^
gpg: /home/ramyasanthosh/.gnupg/trustdb.gpg: trustdb created
gpg: key 296A5510 marked as ultimately trusted
public and secret key created and signed.

gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0  valid:   2  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 2u
pub   1024D/453697B4 2013-12-23
      Key fingerprint = 0511 6477 3F98 75AB 905D  0D05 BCBA 6C69 4536 97B4
uid                  ramyasanthosh (Testing) <techglimpse.newsletter@gmail.com>
sub   2048g/D4EAC9A3 2013-12-23

How to export public key – GnuPG

Now that the key pair is generated, we shall export the public key to be used in an another server for encryption and then transfer the encrypted file to our original server to decrypt using private key. For exporting the public key, run the below command:

[root@catest .gnupg]# gpg --armor --output public-key.txt --export 'ramyasanthosh'

Here ‘ramyasanthosh’ is the uid used during key pair generation.

How to Encrypt file using public key pair – GnuPG

Now we shall use this public key to encrypt the file on an another server, for which you first need to import the public key on that system as shown with the below command:

Mon Dec 23>$ gpg --import file-enc-pubkey.txt

Then you can see the pulic key imported with the below command to list all the public keys available.

Mon Dec 23>$ gpg --list-keys
/root/.gnupg/pubring.gpg
------------------------
pub   1024D/453697B4 2013-12-23
uid                  ramyasanthosh (Testing) <techglimpse.newsletter@gmail.com>
sub   2048g/D4EAC9A3 2013-12-23

Now using this public key we shall encrypt a file:

Mon Dec 23>$ gpg --encrypt --recipient 'ramyasanthosh' sample.txt
pub  2048g/D4EAC9A3 2013-12-23 ramyasanthosh (Testing) <techglimpse.newsletter@gmail.com>
 Primary key fingerprint: 0511 6477 3F98 75AB 905D  0D05 BCBA 6C69 4536 97B4
      Subkey fingerprint: 25C1 48E1 073A 7F61 BFFD  9D14 3F7E 939F D4EA C9A3

Once done, you will find the file name sample.txt.gpg – An encrypted file. Transfer the file to the original server where we generated the key pair.

How to Decrypt file using private key – GnuPG

Now we shall decrypt the encrypted file using private key with the below command. You would be asked to enter the passphrase which you used to generate the key pair.

[root@catest ~]# gpg --output sample.txt --decrypt sample.txt.gpg

You need a passphrase to unlock the secret key for
user: "ramyasanthosh (Testing) <techglimpse.newsletter@gmail.com>"
2048-bit ELG-E key, ID D4EAC9A3, created 2013-12-23 (main key ID 453697B4)

Enter passphrase:

gpg: encrypted with 2048-bit ELG-E key, ID D4EAC9A3, created 2013-12-23
      "ramyasanthosh (Testing) <techglimpse.newsletter@gmail.com>"

That’s done with decryption and you would find the original file sample.txt.

How to Backup your Private key – GnuPG

It is always advisable that you back up your private key and never forget your passphrase! Follow the below command to backup your private key:

[root@catest ~]# gpg --armor --output privatekey.asc --export-secret-keys 'ramyasanthosh'

Was this article helpful?

Related Articles

Leave a Comment