How to protect files in linux with gpg

When working under shared linux machine or environment, sometimes it is necessary to hide or protect some files that contain sensitive information, fortunately there is a tool called GnuPG that most Linux distributions already have pre-installed and we can conveniently make use of this tool and this post is about how easy and quick we can use it for a very basic scenario.

Encrypt and decrypt a file with passphrase

# encrypt and enter a strong passphrase
$ gpg -c filename

# decrypt without entering passphrase as it's cached
$ gpg -d filename.gpg

Optional optimal options

# disable passphrase cache so that decryption requires passphrase
$ gpg -c --no-symkey-cache filename
$ gpg -d --no-symkey-cache filename
# another option is add a line no-symkey-cache to ~/.gnupg/gpg.conf
# so that there is no need to provide command line option every time:
# ~$ cat .gnupg/gpg.conf
# no-symkey-cache

# delete original unencrypted file and
# remove .gpg extension of the encrypted one
$ rm filename
$ mv filename.gpg filename

# change to hidden file
$ mv filename .filename

References

linux security