Data security is an important concern these days and encryption is a very powerful tool to secure the data. In my previous post I talked about how to encrypt a disk. Now we are going to talk about how to encrypt files using GNU Privacy Guard (GPG).
GPG uses public key cryptography. This means that instead of having one key to encrypt and decrypt, there are two keys. One of these keys can be publicly shared and hence is known as public key. The other key is to be kept secret and is known as private key. Anything encrypted with public key can only be decrypted with private key.
How to encrypt files?
Assuming a scenario that user "test" wants to send an encrypted file to me, the user just has to find my public key, encrypt the data and send it to me where I will be able to decrypt the file using my private key and obtain the data. Note that user "test" doesn't need to have GPG keys generated in order to encrypt and send data to me.
Step1: Let us create a text file which we'll encypt:
test$ echo "This is a secret message." > secret.txt
Step2: User "test" needs to find my keys. There are many public servers where one can share their public key in case someone else wants to encrypt the data. One such server is run by MIT at http://pgp.mit.edu.
test$ gpg --keyserver pgp.mit.edu --search-keys aditya@adityapatawari.com
Step3: Once the user obtains my public key, then encrypting data is really easy.
test$ gpg --output secret.txt.gpg --encrypt --recipient aditya@adityapatawari.com secret.txt
The command above will create an encrypted file named secret.txt.gpg which can be shared via email or any other means. Once I get the encrypted file, I can decrypt it using my private key
aditya$ gpg --output secret.txt --decrypt secret.txt.gpg
How to create GPG keys to receive data?
Now assume a scenario where "test" user wants to create a set of GPG keys in order to share the public key and receive encrypted data.
Step1: Generate a key pair. The command will present you some options (stick to defaults if you are not sure) and ask for some data like your name and email address etc.
test$ gpg --gen-key
Step2: Check the keys.
test$ gpg --list-secret-keys
/home/test/.gnupg/secring.gpg
-----------------------------
sec 2048R/E46749BB 2014-11-23
uid Aditya TestKeys (This is not a valid key) <adimania+test@gmail.com>
ssb 2048R/C5E57FF2 2014-11-23
Step3: Upload the key to a public server using the id from the above.
test$ gpg --keyserver pgp.mit.edu --send-key E46749BB
Now others can search for the key, use it to encrypt the data and send it to the "test" user.
To use GPG for saving password, have a look at pass utility. It uses GPG to encrypt passwords and other data and store it in a hierarchical format.