Encrypted Automatic Backups with Public Key Cryptography

Here's how to do encrypted automated backups without having to store the password in the backup script. The script should be self-explanatory (after all, it is 50 lines of comments for just one real line of code).

#!/bin/bash
# File name: backup.sh
# This script automates the process of encrypting a directory for backup.
#
# Instead of using normal password encryption, we take advantage of public-key
# cryptography so that you don't need to include the password in the encryption
# script. This is required if you want to have files automatically encrypted
# with a password remembered only by your biological brain.
#
# It requires a bit of setup:
#
# 1. Generate a public/private key pair (as the user that will run this script):
#   - Run,
#      $ gpg --s2k-cipher-algo AES256 --s2k-digest-algo SHA512 --s2k-mode 3  \
#        --s2k-count 65011712 --gen-key
#   - Choose the "RSA and RSA" key type.
#   - Choose 4096 (or greater) as the key size.
#   - Enter an expiration time of 0 (never expires)
#   - Give the key a name (enter 'invalid@invalid.invalid' for the email).
#   - Enter a password. This is the password that you will need to decrypt the
#     backup files.
#
# 2. Modify the constants in this script:
#   - DIRECTORY:
#       Set this to the folder you want to automatically encrypt.
#   - GPG_RECIPIENT
#       Set this to the ID of the public key generated in step 1.
#       You can find the ID by running
#           $ gpg --list-keys
#       It is the 8-digit hexadecimal number on the 'pub' line corresponding to
#       your key.
#   - OUTPUT_FILE
#       Where to put the encrypted GPG file.
#       If the file already exists, it will be overwritten.
#
# 3. Backup your public key and (encrypted) private key.
#   To decrypt the file that this script generates, you will need the private
#   key and the password you gave in step 1, so it is a good idea to make
#   a backup of your key pair.
#
#   To backup your public key:
#       $ gpg -a --export NAME > public_key.txt
#   To backup your private key:
#       $ gpg -a --export-secret-keys NAME > private_key.txt
#   ...where NAME is part of the name you gave in step 1.
#
#   Because the private key is encrypted with the password, it is safe to store
#   the key backups with the backup file (or even publish them).
#
# DECRYPTING:
#   To decrypt the file generated by this script, run:
#       $ gpg -d -o decrypted.tar <backup file>
#       $ tar xvf decrypted.tar

readonly DIRECTORY=./testing                    # Directory to encrypt.
readonly GPG_RECIPIENT=EAD91475                 # Public key ID.
readonly OUTPUT_FILE=/tmp/encrypted.tar.gpg     # Encrypted file path.

tar cf - -C $DIRECTORY . | \
    gpg -z 9 --batch --yes --encrypt --recipient $GPG_RECIPIENT --output $OUTPUT_FILE

social