There are many use cases for creating encrypted file archives. One such use case is managing file backups. In this short blog post we look into how to use tar and gpg to achieve that.

Creating the archive

Generating an encrypted archive is fairly trivial:

$ tar -cvzf - directory | gpg -c > directory.tar.gz.gpg    

In the above snippet, tar creates a compressed archive of the directory specified, using gzip, and pipes the data to gpg for encryption, before writing to the output file. The ‘-c’ flag instructs gpg to create a prompt for the user to enter a passphrase that will serve as the encryption key.

GPG might throw the following error: inappropriate ioctl for device. This happens when GPG does not know where to read input from. Simply configuring it to look for input from tty (the terminal connected to standard input) fixes the issue.

    export GPG_TTY=$(tty)

Alternatively, the passphrase can be inlined as shown below:

$ tar -cvzf - directory | gpg -c --passphrase a_passphrase > directory.tar.gz.gpg    

The ’–passphrase’ switch will suppress the prompt and will use the next argument as the passphrase.

This is not a safe option as your passphrase is exposed, especially if this is used in a script, or if the commands issued to your terminal are saved in a history record.

Extracting the archive

It’s equally simple to decrypt and decompress the encrypted file as shown below.

$ gpg -d directory.tar.gz.gpg | tar -xvzf -