7.4. Encrypting Files with a Password

Problem

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

Solution

$ gpg -c filename

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:
    #!/bin/sh
    for file in file1 file2 file3 ...
    do
            gpg -c "$file"
    done

    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 ...

Get Linux Security Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.