GPG (PGP) Encryption Command Line Tutorial [Revamped]
For those of you who don't know, Gnu Privacy Guard (GPG) is a tool that can be used to encrypt and decrypt files and messages through the PGP protocol.
I was recently teaching someone how to use GPG, and I realised that there aren't many tutorials online that show you how to use GPG's command line interface, so here goes (this tutorial assumes that you already have GPG installed). There is a GUI version, but doing it this way gives you a nice feeling, doesn't it?
First, you'll want to generate a key for yourself:
gpg --gen-key
You'll be asked to enter a few details. Don't forget these details.
Now before I go any further, let me explain the basics about how PGP works. You generate two keys for yourself: a private key, and a public key. Your private key should be kept safe and no one else except you should have it. Your public key, however, can be sent out to anyone you want.
When someone wants to send a message to you, they need to have your public key. Your public key is used by them to encrypt the file or message that they want to send to you. After they have encrypted the message using your public key, only you can decrypt it with your private key (that's why you only keep your private key to yourself, else anyone could decrypt your messages). Simple, right?
Now, let's take a look at your keys:
To list your public keys:
gpg --list-keys
To list your private keys:
gpg --list-secret-keys
Let's say your name is John Doe, and you want to send a message to Jane Doe. This is how you would do it (note that all names used must be the names you see when listing the keys).
First, export your public key:
gpg --export --armor [email protected] > publickey.asc
Example: gpg --export --armor [email protected] > mypublickey.asc
or
gpg --export --armor yourname > publickey.asc
Example: gpg --export --armor John Doe > mypublickey.asc
Send this file to Jane Doe. Get her to do the same.
To import someone else's public key:
gpg --import publickey.asc
Now that you've imported Jane Doe's key, let's send her an encrypted message.
To encrypt a file to send to Jane Doe:
gpg --encrypt --recipient receiversname filename.txt
Example: gpg --encrypt --recipient Jane Doe secretmessage.txt
or, if the previous command doesn't work:
gpg -e -u "sender's name (you)" -r "name of the receiver's key" filename.txt
Example: gpg -e -u "John Doe" -r "Jane Doe" secretmessage.txt
This will create a file called secretmessage.txt.pgp. Send this to Jane Doe.
Now Jane has received your file. This is how she decrypts it:
To decrypt to command line (meaning that you'll only see the message in the command line, and it won't be saved decrypted to your hard drive):
gpg --decrypt filename.txt.gpg
To decrypt to disk (so that it's saved as a text file on your computer):
gpg filename.txt.gpg
Done!