Recipe 7.4 Encrypting Files with a Password

7.4.1 Problem

You want to encrypt a file so only you can decrypt it with a password.

7.4.2 Solution

$ gpg -c filename

7.4.3 Discussion

Symmetric encryption (-c) is the simplest way to encrypt a file with gpg: just provide a password at encryption time. To decrypt, provide the password again.

By default, encrypted files are binary. To produce an ASCII text file instead, add the -a (armor) option:

$ gpg -c -a filename

Binary encrypted files are created with the suffix .gpg, whereas ASCII encrypted files have the suffix .asc.

Though simple, symmetric encryption has some gotchas:

  • It's not practical for handling multiple files at once, as in scripts:

    A bad idea:
    for file in file1 file2 file3 ...
            gpg -c "$file"

    GnuPG will prompt for the password for each file during encryption and decryption. This is tedious and error-prone. Public-key encryption does not have this limitation, since no passphrase is needed to encrypt a file. [Recipe 7.6] Another strategy is to bundle the files into a single file using tar, then encrypt the tarball. [Recipe 7.18]

  • If you mistype the password during encryption and don't realize it, kiss your data goodbye. You can't decrypt the file without the mistyped (and therefore unknown) password. gpg prompts you for the password twice, so there's less chance you'll mistype it, but GnuPG's public-key encryption leaves less opportunity to mistype a password unknowingly.

  • It's not much good for sharing files securely, since you'd also have to share the secret password. Again, this is not true of public-key encryption.

7.4.4 See Also


    Chapter 9. Testing and Monitoring