Linux tips: Encrypting and decrypting files from command line with gpg
Are you paranoid? Are you afraid that someone is going to get ahold of data they sholdn't have? I am. And because of that I often encrypt files with a gpg key that was given to no one. With those encrypted files I know they are secure to most of the general public. And because I tend to use lengthy passkeys for gpg, cracking them is a challenge.
Naturally I use gpg for all of this. And when I am using gpg I am using it from the command line. It's actually quite easy to use. In this article I will show you how to create a gpg key, encrypt, and decrypt a file. You will find this such an easy task you'll be using it more than you think.Must I install?
More than likely, if you have a modern Linux distribution, gpg is already installed. If you issue the command which gpg and you get something like /usr/bin/gpgreturned, you know you have gpg installed. If you don't see that you can install it by issuing one of these commands:
sudo apt-get install gnupg
yum install gnupg
Once installed you will first have to generate a key. This, too, is done from the command line.
Generate your key
To generate a key issue the command:
Once you enter that you will be asked a number of questions pertaining to your key. These should all be fairly obvious. After you complete the generation of your key make sure you remember the username for the key as well as the passphrase.
Now let's get into the good stuff - encrypting files. To encrypt a file with gpg you will use the command structure:
gpg OPTIONS FILE
Because you are encrypting you will have to use the e option. And because you will want to encrypt the file with a specific users' gpg key you will use the r option. So let's say you are going to encrypt the file TEST.tgz with the gpg key of user jlwallen. To do this you would issue the command:
gpg -e -r jlwallen TEST.tgz
The resulting file would be TEST.tgz.gpg. If you tried to view the file you would instantly see it is now a binary file. If you try to untar the file you would be informed the file is not in gzip format.
Decrypting the file
Decrypting the file is just as easy as encrypting the file. We'll stick with the same example. To decrypt the file TEST.tgz.gpg issue the command:
gpg -d -o TEST.tgz TEST.tgz.gpg
You will be prompted for the passphrase associated with the user encryption key used on the file. The d option indicates you are decrypting the file and the o option indicates what file to output the results to. After this command is issued you will be back to the TEST.tgz file.
Sure there are plenty of gui tools that will make this job even easier. But there are too many instances when needing the command line will enable you to do things you can't do with a gui.Advertisement