Linux: Encrypt and Decrypt Files using GPG

Do you have any files in the server that hold some sensitive information and you only want to open it using a password? That is where GPG helps. GPG stands forĀ GNU Privacy Guard, a tools to encrypt and sign your data and communication, features a versatile key management system as well as access modules for all kinds of public key directories.

In my case, I need to secure one file, which used to store login information for all users inside LDAP. This file will be used by me as reference to reset back the password if user has forgotten. The file name called user_ldap.txt under /home/admin directory.

Since this server also have another sudo users, I will need to secure this file to only who have the password are able to execute and read the files. So I will need to sign the file with GPG and remove the original file. If anyone wants to retrieve the file in the future, they need to enter some password and the original file will be generated.

The file that I want to secure contains following information:

## User credentials for LDAP
Username: mary
Password: M4ksjd(&&s
Department: Accounting
Directory: /home/accounting/mary
Username: ismael
Password: Lpo23S%#s
Department: Technical
Directory: /home/technical/ismael
Username: sazzy
Password: T5sZ&d#R
Department: Human Resource
Directory: /home/hr/sazzy


1. DO NOT LOGIN AS ROOT. At this stage, I login as user admin. Lets sign the file using GPG:

$ cd /home/admin
$ gpg -c user_ldap.txt

You will see something like below. Just enter required information to complete the signing:

$ gpg -c user_ldap.txt
gpg: directory '/home/admin/.gnupg' created
gpg: new configuration file '/home/admin/.gnupg/gpg.conf' created
gpg: WARNING: options in '/home/admin/.gnupg/gpg.conf' are not yet active during this run
gpg: keyring '/home/admin/.gnupg/pubring.gpg' created
cant connect to '/home/admin/.gnupg/S.gpg-agent': No such file or directory
gpg-agent[17211]: directory '/home/admin/.gnupg/private-keys-v1.d' created


2. Remove the original file:

$ rm -Rf user_ldap.txt


3. Retrieve the original file by entering password to the signed file (user_ldap.txt.gpg):

$ gpg user_ldap.txt.gpg
gpg: keyring '/home/admin/.gnupg/secring.gpg' created
gpg: 3DES encrypted data
cant connect to '/home/admin/.gnupg/S.gpg-agent': No such file or directory
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected


4. Read data inside:

$ cat user_ldap.txt

You should able to see the original content of the file as above. Cheers!