Published: |
Copyright © 2005 Brendan Kidwell. Permission is granted to copy, distribute and/or modify this document under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 License.
The information contained in this document is provided as-is. The author shall not be liable for any damages resulting from the use of this information.
For the most recent version of this guide, please see my web site if you're not already there.
This guide will show you how to use the free public key cryptography system, GNU Privacy Guard. GPG provides functions to encrypt and decrypt data and to create and verify signatures, using public key cryptography.
While GPG is available for many different platforms, including Windows, the instructions given here are somewhat Windows-oriented whereever I had to be specific. Most of my peers use Windows exclusively, and those that don't live in Windows are probably at least familiar enough with Windows to understand what I'm trying to convey in the examples.
I make the assumption that you will be using GPG without any add-on enhancements such as WinPT or GPGShell, a couple of graphical front-ends. GPG front-ends are nice, and they save you from having to remember the specific syntax of each command, but sometimes they aren't available, and it's important to have a working knowledge of the underlying system. Users who will be routinely sending and receiving encrypted email will want to find an email program that is tightly integrated with GPG, or has a direct plugin that provides access to GPG.
In this guide, I will show you how to use the most important GPG commands. GPG has many commands and some commands have quite a few variations. Most GPG commands and options have single-letter abbreviations. For the sake of clarity, these short versions will not be used in this guide. For detailed information on all the commands and options available, see the GPG manual, available on the GPG web site, or in the file gpg.man which is included with the software.
I will assume that you know your way around Windows and its Command Prompt. If you need some help there, check out the hints in the end of Appendix A before you continue.
Please note that when I tell you to perform an operation on the command prompt, I assume you have switched to the folder where the files relevant to the discussion are located.
GNU Privacy Guard is available for free from www.gnupg.org for a variety of operating systems, including Windows, Linux, many other flavors of Unix, and Mac OS X.
Note that if you have Cygwin (a suite of software that gives a Windows machine much of the functionality of a Linux machine) you may already have GPG installed. Try running
gpg --version
at the command prompt. If the system says "Bad command or file name
," then you don't have GPG and you must install it.
To install GPG on your computer, first go to the GPG web site and download the Windows package from the Downloads page. Look for the "version compiled for MS-Windows" under "Binaries". The file you download will be a self-extracting archive. Run it and follow the prompts.
Finally, edit your PATH environment variable so that Windows knows where to find the program. In Windows NT/2000/XP, you will find this under the Control Panel → System Properties → the Advanced tab → Environment Variables → System variables
. In Windows 95/98/ME, you will find it in the c:\autoexec.bat
file. Values in this variable are separated by semicolons, so add GPG's path to the end of the variable. For example, if your PATH
variable reads as
c:\windows;c:\utils
then change it to
c:\windows;c:\utils;c:\Program Files\GNU\GnuPG
(Note: "c:\Program Files\GNU\GnuPG
" is where the installer places GPG by default. If you chose to install it in an alternate location, make sure you get it right in your PATH
variable.)
Now you need to make that PATH
change effective. If you're using Windows 95/98/ME, restart your computer; if you are using Windows NT/2000/XP, simply start a fresh command prompt, and close any command prompt windows you had open. Now you should be all set to go. Now try it out. At the command prompt, type
gpg --version
and you should see something like the following output:
gpg (GnuPG) 1.4.2
Copyright (C) 2005 Free Software Foundation, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the file COPYING for details.
Home: C:/Documents and Settings/KidwellB/Application Data/gnupg
Supported algorithms:
Pubkey: RSA, RSA-E, RSA-S, ELG-E, DSA
Cipher: 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH
Hash: MD5, SHA1, RIPEMD160, SHA256, SHA384, SHA512
Compression: Uncompressed, ZIP, ZLIB, BZIP2
Installation in Unix-like operating systems is fairly well covered on GPG's web site --- in fact, most Linux distributions come with GPG prepackaged, so you don't have to worry about explicitly installing it. See Further Reading for more information.
Several people have asked me if it's possible to verify the authenticity of the GPG download, without using GPG itself to do the verifying. This is a useful thing to do if you downloaded GPG from some local mirror and you want to be sure no one's tampered with it.
Yes, this can be done, if you wish to take every available security precaution. First, you need to get a copy the program called sha1sum. The GPG site has a copy available here:
ftp://ftp.gnupg.org/gcrypt/binary/sha1sum.exe
But you should try to find it elsewhere. (Use Google to find a site that has a mirror of it.) The point of this exercise is that we are verifying that no one has tampered with your download of the GPG installer. If someone tampered with that, they might have tampered with sha1sum.exe as well since they both reside on the same FTP server.
Download this file and put it somewhere convenient. You can put it in your system32
folder under your Windows
folder; I prefer to put such utilities in their own separate folder called c:\utils
, and then I make sure utils
is in the PATH
environment variable (as explained above.)
Once you have sha1sum ready, open a command prompt window and go to the folder where you downloaded the GPG Zip file. Type something like the following command:
sha1sum gnupg-w32cli-1.4.2.exe
(Be sure to specify the actual name of the GPG installer file you downloaded. If a new version has been released, it will have a different name.) sha1sum will respond with a hash value, like this:
8394920be8d2daa764e94d4bd5869853a3f293b8 *gnupg-w32cli-1.4.2.exe
Make a note of that number.
Now, go back to the GPG web site and find the page called "Integrity Check" in the "Download" section. At the bottom of the page, you should find "SHA1 Sum Summary" which should include a number for the file you just ran through sha1sum. If the number matches, then congratulations --- you have a valid copy of GPG.
(Hint: These SHA-1 sums are big numbers. To make it easier to compare them, you might try copying yours and the one from the GPG web site into a text editor, one above the other.)
GPG uses public key cryptography for encrypting and signing messages. Public key cryptography involves your public key which is distributed to the public and is used to encrypt messages to be delivered you and to decrypt signatures you have created, and your private key which complements your public key by allowing you to decrypt messages you receive and to encrypt signatures. Together, these are referred to as a key pair.
When you create a key pair, both your public and private keys must be stored on your computer. This creates a security risk, because anyone who can gain access to your private key can decrypt your messages and impersonate you. You can't commit your private key to memory and erase it from your computer --- it is far too long (usually at least 1024 bits --- that's like memorizing a 300-digit phone number!) Besides, even if you could memorize it, it would take too long to type it out each time you wanted to use it.
The practical solution to this problem is to go a step further and actually encrypt your private key using a reasonably short passphrase as a key for the key; this is what GPG does. Each time you perform an operation involving your private key, GPG reads the encrypted key from the disk, prompts you for your passphrase, decrypts the key in memory, and finally uses it. In order for this system to work, you must have a cryptographically strong passphrase --- something that can't be guessed or brute-force attacked. For example, "orange" is so short that a dictionary attack will find it in seconds, and your girlfriend's full name is a poor choice because anyone who knows you might guess that you used it as your passphrase.
What you really need is a really good source for a random string of words.
You might try using your computer to generate a random string of words for your private key passphrase, but that's generally also a bad idea because computers are theoretically incapable of producing truly random numbers. The best solution is said to be gambling dice and a word list, such as Diceware.
The procedure is fairly simple. The author of the Diceware wordlist compiled a text document containing about 8000 short words, indexed by a five-digit base 6 number, with digits ranging from 1 to 6 instead of 0 to 5 --- perfect for looking up numbers randomly generated by the roll of a die.
Download the word list from the Diceware web site and open it in a text editor (such as Notepad.) Now roll the a die five times and record the results. Look up that number in the word list and write down the word that corresponds to it. For example, say you rolled 3,5,6,2,3. You would find word number 35623 in the word list, "ladle," and record that. For a reasonable compromise between ease of memorizing your passphrase and security, the author of Diceware recommends you repeat this entire process five times, to produce a five-word passphrase.
Now that you've got your passphrase, you're ready to generate your personal key pair. At the command prompt, type
gpg --gen-key
GPG responds with a menu asking what kind of key pair you want to generate. Choose the default, which is "DSA and ElGamal" as of this writing in 2005.
Next, it asks you the size of the key. Again, choose the default, which is "1024" as of this writing in 2005. If your key is too small, it is easier to crack; if it is too large, then every operation that uses it may execute too slowly.
The next prompt asks you when (if) the key should expire. Letting the key expire after a certain amount of time adds a little bit of security, because documents encrypted after this time are not connected with the old key in any way. The tradeoff, of course, is that everyone you correspond with must fetch your new key when the old one expires. At the prompt, choose a reasonable time period for the lifetime of your key, or select "key does not expire."
Now you enter the Real Name and Email Address which will be used to identify the key in everyone's key collections, not just yours. If you don't feel comfortable attaching your full real name to your key, be sure to pick something unique so that your key won't be confused with anyone else's.
Finally, enter the passphrase you generated using Diceware. GPG will not give you any feedback as you type your passphrase --- it won't print asterisks or spaces as most password input functions do. This is yet another security measure.1 After you enter and then confirm your passphrase, GPG will start doing some number crunching to generate all the random bits it needs in your key pair. It uses all sorts of sources inside the computer to simulate randomness, including console input --- so if you want to speed up the process, type some random characters on the keyboard.
The easiest way to publish your public key is to simply post it on a web page or email it directly to people who need it. Of course, this is also one of the least secure ways of doing it --- plaintext email and web pages can be (theoretically, at least) subject to man-in-the-middle attacks.2 More advanced methods of key exchange involve things such as webs of trust and key servers, which are beyond the scope of this guide. If you don't believe specifically that someone will try to attack you, you may be comfortable with the method described here.
You have been warned. The exchange of public keys without a trusted intermediary can be subject to a man-in-the-middle attack.
To transmit your public key over the Internet, the first step is to export it to ASCII format. Open a command prompt window and go to a folder where you want to place the exported key. Type
gpg --armor --output "key.txt" --export "YOUR-NAME"
You may change key.txt
to some other filename if you'd like. YOUR-NAME
can be your Real Name or your Email Address; GPG will find it either way. The --armor
option instructs GPG to format the output "armored" for plain-text transmission. This makes it easy to copy and paste the key to and from web pages and email messages. The --armor
option applies to most GPG commands that produce any kind of output.
Open the output file, key.txt. You should see something resembling this:
# Example key display; do not use
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.1 (MingW32)
mQGiBD53m34RBAC6GXvDFWD3a+GOkQKubz5Koq9lks9d+gel29/sA5kqSfQnoaeR
qdTKLlB+oNsVjDX/Szfi3fsrK5zmKKZVHv3JO4DkxtABf4HgfaGkpav2PvXevYoB
YWSGTclHOHN5D3xsbIX6wvunkNhllcqrFlC3braG2tQnt2+PMk1gMA2jhwCg7qam
RtC27n0RY25jMfM/fESTImcD/1OtFwRtchqjPvl2IHSCBlltJyksuStevOfAFnc1
p3H+JqdUiKVf8oAF4NP4KarXL34xPCJXLKlBwHC3SH8powy2HX0mhsCjvVQQeLOP
fU3Q5DJxGM16hfmqlD1k4a7NUjnXwlCrce4rVToFbCnLrJTVoMDyNhowrXPbPCVM
N3FNA/0Uciz19raTBGkwo6kpsicpZG7Mk4eGFK5ssWxPxlLYoQ7yzgekWd9h6zBT
IQpdkatzdNf7xDEaUEBhO4vD7Il02OLigro95N5savsH9StTNCsJgmaiwtX5hxuF
WpW974xgfCmbGOPnbs1QTuyT85VllLxHI5fsGOYKCd/qo8H4nLQHQksgVGVzdIhZ
BBMRAgAZBQI+d5t+BAsHAwIDFQIDAxYCAQIeAQIXgAAKCRDCVd5vH6A96m7fAKDs
YVhdSqNn+u/rkj1pU6kFldY0JwCcCCXth72RJ9tAIz5gq9M3m6y2+7q5AQ0EPneb
gRAEAIb/sxLIAKaahBfBpGxpn3ZKhvug1z6yP7jLWFNLFugaakYjm5LXsI5Hpj06
mAE2fJPUNc1of0ZaK4La3XA8l/nVaadDP6FDqnxuPv3ne5JAxcK76ecT+m0ljQXZ
oVnUkUqeNnwtcIs0fmmXnaeD68OHdidYsIuuEDhrFvPAT6cfAAMFA/923B1Bm4NR
riLy8QxYNuTxImtxoVg4NtfnYuHWyoxP1Ic3C1nZD2+fxf2685KNKx+3ZwaE81zN
ZNl0kNdFhB24Vmr6HM5C+eSlHj8C+LOUdP1A/9Un5utceg/qjNYkRXJx5mjyCizh
Gg/+1mLB5e+OA9Tl5R+96PKPFov+UjNPu4hGBBgRAgAGBQI+d5uBAAoJEMJV3m8f
oD3qewYAoNFRCBVfbX+LKxmWOZoqyQhB7jfnAKDDOCzQhZLZmrf0Uqdk6yj+HDm0
rA==
=+DfK
-----END PGP PUBLIC KEY BLOCK-----
Copy the entire contents of that file, including the lines beginning with -----
, and paste them on a web page or in an email message to someone else. That's all it takes to export your public key.
Note: it is possible to export your private key in the same manner, with the --export-secret-keys
instead of --export
. This is useful for backup or for transferring it to another computer, as long as you know what you're doing and you can be sure the new copy will be secure. Make sure you don't ever accidentally publish your private key! Before you publish a key in ASCII form, check that the first line has the word PUBLIC
, not PRIVATE
.
Keeping your GPG key files safe is just as important as remembering your passphrase --- your passphrase does you no good if you don't have a copy of your full private key on your computer. If your key file is destroyed, there is absolutely no way to reconstruct it, short of executing a cryptanalysis on your own data. To back up your GPG keys, including all your private keys, locate the files pubring.gpg
, secring.gpg
, and trustdb.gpg
(They are in C:\Documents and Settings\[your name]\Application Data\gnupg
by default.) and copy them to a safe location, such as a CD-R disc. Store this disc in a safe place where potential attackers won't likely be able to find it. (Of course, your keys are safe long as your attacker doesn't know your passphrase.)
Now, you are finally ready to actually encrypt something.
The basic encryption and decryption procedure in GPG is this: The sender determines the recipient of a file, acquires that recipient's public key if he hasn't already done so, and then runs the plaintext through GPG along with this key to obtain the ciphertext.3 When the recipient wants to decrypt the file, he applies his private key to the ciphertext to obtain the plaintext.
In other words:
plaintext + recipient's public key → ciphertext
and
ciphertext + recipient's private key → plaintext
In fact, the sender and recipient aren't always different people. One important use of GPG is to encrypt your own data, storing the ciphertext and destroying the plaintext. This is an excellent defense against physical attacks on your computer or your local file server.
Choose a file you want to encrypt. For example, let's assume you have diary, where each month is a new file, and you're done with February 2003, which is called diary 2003-02.txt. Suppose you want to encrypt this file and then put it away in an archive folder or a CD-R disc. At the command prompt, type (all on one line)
gpg --recipient "YOUR-NAME" --output "diary 2003-02.txt.gpg"
--encrypt "diary 2003-02.txt"
Don't forget to fill in YOUR-NAME
with the actual name you attached to your key. Always remember the --output
option when you use an encryption command in GPG; if you omit this option, the output will be dumped to the command prompt window instead of to a file. Finally, notice that the command (usually an action verb) always goes in the last position on the GPG command line, after any options. Now diary 2003-02.txt.gpg
will contain a seemingly random string of bytes. You can look at it with Notepad if you'd like.
There is a similar command, --encrypt-files
, which will automatically choose and name an output file for you. But the filename it chooses will be missing the extension of the plaintext filename (.txt
, .jpg
, .zip
, etc.) so I don't use it, myself.
Now, suppose a year from now you're feeling nostalgic and you want to read February 2003's diary. You would copy the ciphertext back to your workspace on your computer, and type the following at the command prompt:
gpg --decrypt-files "diary 2003-02.txt.gpg"
GPG will look up your private key and prompt you for the passphrase. Provided your private key is still installed on your computer, and you still remember your passphrase (you didn't write it on a Post-It and stick it on your monitor, did you?) you will get back the original plaintext exactly as it was before you encrypted it. If you want to decrypt a short file and display it immediately in the console, you can use the --decrypt
command instead of the --decrypt-files
command.
Encrypting your own files is useful, but a more common use of GPG is to send encrypted data to someone else. Before you can use GPG to encrypt a file for someone else, you need to get their public key.
As I said before, two convenient ways of getting someone's public key are email and personal web pages. As an example, you can download my public key from my web server; try it right now. Go to my public key page. Copy all the text you see and paste it into a text file using Notepad. Suppose you named the saved file brendan.txt. At the command prompt, type
gpg --import "brendan.txt"
GPG should say
gpg: key A3CA0378: public key "Brendan Kidwell < brendan@glump.net >" imported
gpg: Total number processed: 1
gpg: imported: 1
Notice that GPG wasn't distracted by all the extra text on the page. It looks for the telltale "BEGIN PGP PUBLIC KEY BLOCK
" line and ignores everything outside that block of text.
One more step you need to perform after you've imported a key from an external source is set the trust level on it. GPG is paranoid, and if you use the key right now as it is, you will get a warning message saying that you haven't established the authenticity of the key. To make this warning message go away, use the GPG --edit-key
command to set the trust level:
gpg --edit-key "Brendan Kidwell"
GPG will enter the interactive key editing mode. Enter the command trust
and select level "5) I trust ultimately." Then enter quit
to save your change.
Now you're ready to encrypt the file. Let's assume you have a file you want to send to me called message to brendan.txt. At the command prompt, type
gpg --armor --recipient "Brendan Kidwell" --output "message to brendan.txt.asc" --encrypt "message to brendan.txt"
GPG will produce a file calle message to brendan.txt.asc
, whose content you can copy and paste into an email.
Alternatively, if you need to send a particularly large file, you should use the encrypt command without the --armor
option:
gpg --recipient "RECIPIENT" --output "FILE.gpg" --encrypt "FILE"
and instead of pasting FILE.gpg
into the body of the email, include it as an attachment. Make sure the name of the file doesn't reveal anything that should be secret.
[2007-03-02] This section used to have an invitation to try sending an encrypted message to me. I'm sorry, but I don't personally use GPG much anymore, so I never have it ready when someone sends me a GPG-encrypted message. Instead of emailing me, try emailing yourself. You can setup another computer and only give it your public key; then from that computer send an encrypted message to yourself and receive it on your first one and see if you can decrypt it. (See Section 3.4 for instructions on how to export your public key so you can install it on the other computer.)
How you deal with an encrypted email message which you have received depends on how it was sent to you. When you receive an encrypted message, its body might contain
-----BEGIN PGP MESSAGE-----
followed by a string of random-looking characters. Or the message might simply have an attached file whose name ends with ".gpg
" or ".pgp
."
If the encrypted data is in the message body, save the entire message to a file, and end the file name with .asc
. If you know that the encrypted data is some binary format, include the file extension before the .asc
. For example, if you know the message contains an encrypted Microsoft Word file, you would name the file message.doc.asc
. At the command prompt, type
gpg --decrypt-files "FILE.asc"
where FILE.asc
is the filename you used to save the message. GPG will tell you who the file was encrypted for and prompt you for the passphrase. If the file wasn't encrypted using your public key, GPG give up and tell you that it doesn't have the private key needed to decrypt this file. If the decryption succeeded, you should get the original file back, with the name you gave it, minus the .asc
extension.
Remember, if you know the encrypted data is just a short text message, you can display it on the console instead of storing it in a file with the "--decrypt
" command:
gpg --decrypt "FILE.asc"
If the encrypted data is in an attached file, save that file to your computer. At the command prompt, type
gpg --decrypt-files "FILE.gpg"
where FILE.gpg
is the name of the file you saved. (If the message was created using PGP,4 the name of the attached file will probably end with .pgp
instead.) Again, GPG will only work if you have the private key needed to decrypt the file.
Sometimes, you'll want to send an encrypted file to more than one person. This could create a problem, though, because no one should be sharing a private key with anyone else. You could always make a separate encrypted file for each recipient, but this can get tiring if you need to send a file to many people.
There is a better way: GPG allows you to specify a list of people who may be able to decrypt a file. GPG will then use all of those individuals' public keys to encrypt the data in such a way that any one of their private keys (and no one else's) can decrypt the data.
The syntax is straightforward. Just add more --recipient
options to the command line. Suppose you wanted to encrypt the same message as in Subsection 4.3.2 above, but wanted to send the message so that both you and I could decrypt it later. You would type the following at the command prompt:
gpg --armor --recipient "Brendan Kidwell" --recipient "YOUR-NAME" --output "message to brendan.txt.asc" --encrypt "message to brendan.txt"
and then copy the output file into an email message as before.
Sending encrypted email this way can make it easier to manage your saved correspondence. Normally when you send plaintext email, a copy of the sent message is saved somewhere in your email software (unless you specified that you don't want to save copies.) You can always go back and review your sent email to recall what was said. If you specify your target and yourself as recipients when you prepare an encrypted message, then you can go back and review it in your sent email collection whenever you need to, with only the added step that you need to decrypt it before you view it. You needn't save a separate plaintext copy of the message, nor do you need to make another copy encrypted for yourself.
Specifying several recipients does not adversely affect the size of the encrypted data. I tried encrypting a large (\~8MB) compressed binary file for one and then two recipients. The difference in the size of the output was only a few hundred bytes.
Often it is desirable to verify the origin of data, whether it is encrypted or not. GPG's signature functions provide a means of verifying authenticity.
The theory is simple. Public and private GPG keys work either way. Once you have encrypted data with one of the keys in a pair, it can only be decrypted with its complement in a the same key pair. Normally GPG operates by encrypting with the public key so that only the recipient can decrypt the data using his private key.
Digital signatures work the other way around; data is encrypted using the signer's private key. If someone receives the file and succeeds in decrypting the data with the signer's public key, then presumably, the data must have been encrypted by that signer. Therefore, the signer must have created the data himself, or at least approve of its contents in some way (depending on the nature of the actual data.) A digital signature is just as useful as a physical one made with a pen, and arguably, it is more secure.
When GPG creates a digital signature, it doesn't encrypt the entire file with the signer's private key. Instead, it computes a hash value,5 encrypts that, and appends it to the original data as the signature. This makes it possible to create signed files that are readable without any encryption software, and aren't significantly larger; GPG is needed only to verify the authenticity of the file.
To verify a signature, GPG reads the data that was signed and computes its hash value. Then it decrypts the signature, using the signer's public key, to obtain the true hash value. If the two hash values match, the signature is valid and the data you have is exactly the data the signer had when he created the signature.
Suppose you want to send a message to someone in such a way that they can prove it was you who authored the message. First, compose the message in a text editor and save it as message.txt
in a convenient folder. Then, at the command prompt, type
gpg --local-user "YOUR-NAME" --clearsign "message.txt"
Since this operation involves your private key, GPG will prompt you for your passphrase. After that, GPG will compute a signature and write a new file called message.asc
containing the plaintext and the signature. The contents of this file can be copied into an email and sent to the intended recipient.
As an example, here is message that I have signed:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
This is a test message signed by Brendan Kidwell.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
iD8DBQE+fnwc4lxlBKPKA3gRAq13AJ4557Md6xF15OoEDyIIB+UvDQKwmwCfcrCY
na12Ng9W4K5mP1ZWEueNjCo=
=73hB
-----END PGP SIGNATURE-----
Suppose you receive a message like the one produced in the previous section. Or you might find such a message posted on a public web site or electronic message board. Before you can verify its signature, you need to obtain the signer's public key and install it on your computer. This procedure is described in the previous chapter, under the heading "Importing the key."
If the message to be verified is contained in an email, export it to a text file. If the message is displayed on a web page or some other online medium, save it as a text file (named, for example, message.txt
.) Then type the following at the command prompt:
gpg --verify "message.txt.asc"
GPG will locate the signer's key if you have it, and use it to check the signature and report whether or not it is valid.
If you're reading the online version of this document and you've already installed my key, you can try copying the test message displayed in the previous section into a text file and verifying the signature with this procedure.
Text messages can have signatures appended to them without disrupting the contents of the message too much, but binary files such as Microsoft Word documents and Zip archives can't have arbitrary data attached to them. To sign binary files, it is costumary to have GPG create a separate signature file. Suppose you have a Zip archive you want to sign, called monthly report.zip
. Type the following at the command prompt:
gpg --local-user "YOUR-NAME" --output "monthly report.zip.sig"
--detach-sign "monthly report.zip"
Again, GPG will prompt you for your passphrase and then it will generate a signature in monthly report.zip.sig
. If you were going to email this to someone, you would attach both files to the email message.
Now suppose you're on the other end and you receive a file with a signature like this via email. Save both files to the same folder and type the following at the command prompt:
gpg --verify "monthly report.zip.sig"
GPG will verify the signature of the file using the signer's public key and report whether or not it is valid. Again, the person doing the verifying must have a the signer's public key installed.
Software distributed over the Internet is often signed in this manner --- especially software that relates to security. A user can download a large installation package quickly from a local site, which need not be trusted. After the download is complete, he can go back to the creator's web site and fetch a public key and the signature for the installation package and use them to verify the package's authenticity.
It is possible to encrypt and sign a file at the same time. Use this command to encrypt and sign a file:
gpg --local-user "YOUR-NAME" --recipient "RECIPIENT" --armor --sign
--output "FILENAME.asc" --encrypt "FILENAME"
This produces an output file named FILENAME.asc
.
To decrypt such a file, simply run
gpg --decrypt-files "FILENAME.asc"
GPG will see that the file has been signed and it will automatically verify it if it has the signer's public key.
And, as always if you prefer simple binary output, omit the --armor
option.
GPG can be integrated into an existing programming project, with a small amount of effort. This chapter will explain how to modify your program so that it can use GPG.
Suppose you have created a data entry application which will be installed on several client's machines. Suppose you want this application to be able to send updates to a central location. Sending the data over the Internet to an FTP server would be a convenient way to do this, but a major disadvantage of the FTP protocol is that it has very little security; file are transferred over an unencrypted channel. One solution to this problem is to include GPG with your program, and use GPG to encrypt the data before it is sent.
As a software developer, you probably don't want to require your client to install GPG by himself and then import the necessary keys. This isn't necessary. All you have to do is copy the main executable file, gpg.exe
, to your program's own folder and prepare it correctly.
Whenever GPG runs, it assumes all of its keys are located in the Home Directory. On a Windows machine, this is C:\Documents and Settings\[your name]\Application Data\gnupg
; on a Unix machine (or a Windows machine with GPG installed under Cygwin), this is a hidden folder called .gnupg
which is a subfolder of the home folder of the current user. When your application calls its own special copy of GPG, you should tell GPG to use a different folder for its home folder, such as the folder where your application and GPG are located.
To prepare your application's special copy of GPG, you will have to install the necessary public and private keys into it. Which keys you install will depend on what GPG functions your application will use. Suppose you want your application to be able to send encrypted files to a user named Administrator. Export Administrator's public key to a text file called administrator.txt
and copy that text file into your application's folder. At the command prompt, in your application's folder, type
gpg --homedir . --import "administrator.txt"
The --homedir .
option tells GPG to use the current folder as its Home Directory.
Don't forget to set the trust on the key you just imported. At the command prompt, type
gpg --homedir . --edit-key "Administrator"
Enter trust
, then 5
, then quit
.
When your application is ready to send data, it should package it up in some convenient way into a single file. If you will have more than one user uploading data to you, you should ensure that each one uses a unique filename to avoid name collisions on the FTP server. Suppose your application exported its data to a file called update\_user001.dat
. It would then use the operating system to call GPG with the following command (being sure to execute it in the application's own folder):
gpg --homedir . --recipient "Administrator" --output "update_user001.dat.gpg" --encrypt "update_user001.dat"
At this point, you will have an encrypted file named "update\_user001.dat.gpg
" and you will want to send it to your FTP server. Windows has a convenient console-mode FTP command that supports rudimentary scripting. At the command prompt, you can type ftp
and you will get a prompt saying, ftp>
. The basic commands inside FTP are as follows:
open hostname | Open a connection to hostname | |
user username | Initiate login process | |
ls | List contents of current folder | |
cd folder name | Change to a different fol | td> |
bin | Set binary mode for file transfer | |
get filename | Download file | |
put filename | Upload file | |
quit | Exit FTP |
So, to upload a file from within your application, you need to create a script file with the following lines:
open HOSTNAME
user USERNAME
PASSWORD
cd /DESTINATION-FOLDER
bin
put update_user001.dat.gpg
quit
Needless, you would have to replace the words in all-caps with the actual values that belong there. Suppose you put these commands in a file called ftp.script
. You would want to run this script and capture the output to a log file so your application can examine it to see if the file transfer was successful. To do this, your application should run the following command:
ftp -s:ftp.script >ftp.log
Then your application should search the contents of the file ftp.log
for signs of success or failure. The way I do this is I read the entire file into a string variable and then search that string for the words
226 Transfer complete.
(with that exact capitalization). If the message does not appear, my program assumes the transfer failed and displays an error message, with the opportunity for the user to inspect the log file himself.
It is very important that the message being scanned for in the log file actually appears there if the transfer was successful. You should verify that this is exactly what your FTP server will say when a transfer is complete.
I have created a Microsoft Access application that demonstrates the secure data transfer scheme outlined above. If you have Microsoft Access, go to my web site and download the demo application and try it out.
Even if you've never programmed Microsoft Access before, don't be afraid to download this demo application and take a peek. Programming in Microsoft Access is done in the Visual Basic language, and the source code is embedded in the database file, free for all to see. Exact details of where to look inside the demonstration application can be found in the application's readme file.
Several readers have asked me about how to have an automated script decrypt files. The problem, of course, is that whenever you perform a command involving a private key (decrypting or signing) GPG stops to prompt you for the passphrase on that key --- assuming that key is properly installed. There is no fully secure way to get around this prompt and make the script run without user interaction.
My reasoning behind that statement is straightforward: All of security protocols built into GPG depend on the passphrase, which is actually a part of the private key. As long as the passphrase is not known, it is virtually impossible to crack the security and make use of the private key. If you are trying to write a decryption script that requires no user intervention, you must store the passphrase on the computer, which makes your private key vulnerable.
That having been said, I'm sure there are many people who aren't very concerned about the security of their local files. That may or may not be a valid stance to take, but you have been warned.
There is an option in GPG that specifies that the required passphrase be read from a particular file handle, instead of from the keyboard. The option is --passphrase-fd
and it is followed by the number of the file handle. It's probably safest (in terms of stability) to use file handle 0, which is always the standard input stream.
Suppose you have prepared a file called passphrase
which contains the passphrase required for a particular operation. Put the following line in your script:
type passphrase | gpg --passphrase-fd 0 OPTIONS COMMAND
(Of course, you would substitute OPTIONS
and COMMAND
with actual GPG instructions.) The pipe character, |
, specifies that Windows should take the standard output (which is normally directed at the display) of the first command and pipe it into the standard input (normally the keyboard) of the second command.
(Unix/Linux users: use the cat
command instead of type
.)
Alternatively, you can use the echo command to send the passphrase to GPG, without saving it to a separate file on disk:
echo PASSPHRASE| gpg --passphrase-fd 0 OPTIONS COMMAND
Make sure that you have a single space after the echo
command, but no space before the pipe character. Each character between that first space and the pipe is sent to GPG as part of your passphrase.
Be aware that this really isn't any safer than saving the passphrase in a file on the disk. Someone might be able to retrieve the passphrase from whatever part of your program generates the above system call. Many other attacks are possible as well; there might be a way to snoop the data as is passes from your program, through echo
to GPG.
Relevant chapter numbers in the full guide are displayed in parentheses after each item.
gpg --version
Find out what version of GPG you have installed (2)
gpg --gen-key
Create a new key pair (3)
gpg --armor --output "KEY.txt" --export "YOUR-NAME"
Export your public key to a text file KEY.txt
(3)
gpg --import "KEY.txt"
Import the keys found in KEY.txt
(4)
gpg --edit-key "NAME"
Edit the key for NAME
. In edit mode, use the "trust
" command to set the trust level (4)
gpg --recipient "RECIPIENT" --output "FILENAME.gpg" --encrypt "FILENAME"
Encrypt FILENAME
using RECIPIENT
's public key (4)
gpg --amror --recipient "RECIPIENT" --output "FILENAME.gpg" --encrypt "FILENAME"
Encrypt a file and output text suitable for email (4)
gpg --decrypt-files "FILENAME.asc"
or
gpg --decrypt-files "FILENAME.gpg"
Decrypt FILENAME.asc
or FILENAME.gpg
verify a digital signature if present, and output to FILENAME
(4)
gpg --local-user "YOUR-NAME" --clearsign "FILENAME"
Create digital signature and output plaintext plus signature to FILENAME.asc
(5)
gpg --local-user "YOUR-NAME --output FILENAME.sig --detach-sign "FILENAME"
Create separate digital signature file for FILENAME
(5)
gpg --verify "FILENAME.asc"
Verify the digital signature found inline in FILENAME.asc
(5)
gpg --verify "FILENAME.sig"
Verify the digital signature for FILENAME
contained in FILENAME.sig
(5)
gpg --armor --local-user "YOUR-NAME" --recipient "RECIPIENT" --sign --output "FILENAME.asc" --encrypt "FILENAME"
Encrypt and sign FILENAME
, with text output to FILENAME.asc
(5)
gpg --homedir . SOME-COMMAND
Use the current folder as the home folder, useful for calling GPG from an application. (6)
X:
Switch to drive letter X
cd FOLDER-NAME
Switch to the folder "FOLDER-NAME
"
cd \
Go to the root folder of the current drive
cd ..
Go to the parent folder of the current folder
dir
List the contents of the current folder
exit
Close this command prompt window
This security measure will make it harder for someone to gain any information about your passphrase. If GPG gave you feedback with asterisks, an attacker might be able to observe how many characters are in your passphrase by looking over your shoulder. ↩
A man-in-the-middle attack would involve a third party replacing the public key before the person who wants it tries to retrieve it. For example, suppose Eve wants to intercept a message Alice will send to Bob. Bob publishes his real public key on his web site and Eve immediately breaks in to the web server and replaces the key with her own fake public key for Bob. Alice downloads what she believes to be Bob's public key, but is in fact Eve's replacement. Alice uses this key to encrypt and send a message to Bob, which is intercepted by Eve, decrypted by Eve's private key and read, reencrypted with Bob's real public key, and finally sent on to Bob --- with no one the wiser. Needless to say, it would take a very determined attacker to pull this off in practice. ↩
In this context, the words plaintext and ciphertext don't necessarily refer to simple text; plaintext can be absolutely any block of data, such as a text, an image, sound, or video. ↩
PGP is a commercial software tool that implements of the same algorithms and protocols used in GPG. Actually, GPG descended from PGP. ↩
A hash value is a relatively short string of data that represents a large string. A hash function computes the hash value of a string of data. An ideal hash function works only one way; it is easy to compute a hash value of a given data set, but it is incredibly difficult to find a data set that will produce a given hash value. Also, hash functions used in cryptology must be very sensitive to small changes in the data, so that you can be sure that if someone changes the data, the hash value will be different. For more information, see "Hash Function" in Wikipedia. ↩
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
This policy is subject to change at any time and without notice.
Reader-contributed comments on Glump.net are owned by their original authors, who reserve all rights.
Comments rules:
Comments (11)
Hello, cant you tell me how cant I encrypt a File using TDES?
I tried with the "gpg --recipient "Darth Vader" --output EncryptedFile.gpg --encrypt localhost.2018-03-19.log" and It worked but I don't know under which algorithm is this encrypted file generated
Thanks
This is a wonderful post on GPG. I am able to test the GPG just by going through the notes.
A team gave me a public which is been use from a production server. So i use that public key to test the files they gives me.
error is: gpg: decryption failed: no secret key
i did all you say, import that key .. what I miss?
Can anyone help me on this?
How to solve this?
I am using this command to decrypt a file.
gpg --batch --yes --passphrase "passphrase" --output J:\PGP\tsc.pgp
It's resulting to the following error:
gpg: Fatal: zlib inflate problem: invalid distance too far back
Thanks in advance.
Two questions (and then feel free to delete this post):
1. There's a JPEG (~5.7 KB) appended to your public key. Can you explain why and for what purpose it's there.
2. I was able to import your public key (confirmed via --list-keys) and assigned the ultimate trust level, but when I attempt to verify your sample signature it comes back:
"gpg: Signature made 03/23/03 23:31:40 Eastern Daylight Time using DSA key ID A3CA0378
gpg: Can't check signature: No public key"
Is this a problem on my end, or is it because the key doesn't match the signature?
1. The jpeg is a picture of me so you know whose key the key claims to be if you met me in person. I've seen a few other people do that and one of the GUIs I used years ago encouraged it.
2. Different key. The key I used to make that signature in the article text is old and lost. I need to update the article.