Encrypt tar.gz file on create

Pack your_dir in a encrypted archive your_archive.tgz.gpg (symmetric encryption):

tar -cz your_dir | gpg -c -o your_archive.tgz.gpg

Unpack it:

gpg -d your_archive.tgz.gpg | tar xz

See the docs of GPG for how to use asymmetric instead of symmetric encryption.


The following process encrypts the file on local disk first, and can then be sent over the network (or stored however needed)


First, generate public and private keys (done only once):

openssl genrsa -out key.pem 2048
openssl rsa -in key.pem -out key-public.pem -outform PEM -pubout

Then, at each backup:

  1. Generate long random passphrase, save in file

    • echo -n "Tl4R6dnvWXiDeXr1LtpCNkyLG1" > key.txt
  2. encrypt file with passphase

    • openssl enc -aes-256-cbc -pass file:key.txt < UNENCRYPTED_FILE > encrypted.dat
  3. encrypt passphrase with public key

    • openssl rsautl -encrypt -pubin -inkey key-public.pem < key.txt > enc.key.txt

Then save encrypted.dat AND enc.key.txt where desired.


To decrypt:

  1. Decrypt encrypted passphrase with private key

    • openssl rsautl -decrypt -inkey key.pem < enc.key.txt > key.txt
  2. Decrypt file

    • openssl enc -aes-256-cbc -d -pass file:key.txt < encrypted.dat > UNENCRYPTED_FILE

This is a lot longer than Florian's anwser, but I decided to use it so I can better understand the process, and not depend on server-dependent GPG configuration variables, etc. I also couldn't find any useful GPG documentation.


I do this with asymmetric key encryption. That means I have a public key (that I can share with anyone I'd like to send me encrypted packages) which allows me to encrypt the package. I also have a private key (that I do not share) which allows me to decrypt the package.

My commands to encrypt the current working directory: the -e to encrypt, the -r to specify a "recipient" or key to use, the -o to specify the output file.

$ tar -cvz . | gpg -e -r ABCD1234 -o backup.tgz.gpg

And to decrypt to the current working directory:

$ gpg -d backup.tgz.gpg | tar -xz

Or to decrypt to a standard tgz file for later unpacking:

$ gpg -o backup.tgz -d backup.tgz.gpg

Of course, this only works if I have already generated a public-private key pair and installed it with gpg. In my case, I have done so using Digital Ocean's guide at https://www.digitalocean.com/community/tutorials/how-to-use-gpg-to-encrypt-and-sign-messages-on-an-ubuntu-12-04-vps. The ABCD1234 in the encryption command refers to one of the public keys installed on my system. This guide also covers how to share your public key and install others' public keys to send and receive encrypted files.