Create Compressed, Encrypted Archives with tar + gpg on Linux
avatar

Need to back up or share sensitive files on Linux? A simple, time-tested pattern is:

  1. archive with tar,
  2. compress (e.g., gzip), and
  3. encrypt with GnuPG (gpg).

Below are the most useful one-liners for both password-based (symmetric) and public-key (asymmetric) workflows, plus how to decrypt and list contents without creating intermediates.

Symmetric encryption (password)

Use a passphrase you’ll remember (or store it in a password manager). This creates a compressed (.tar.gz) archive and pipes it straight into gpg for encryption:

# Create: directory -> tar.gz -> gpg (prompted for passphrase)
tar -cvzf - /path/to/dir | gpg --symmetric --output secret.tar.gz.gpg

# Decrypt + extract back to current directory
gpg --decrypt secret.tar.gz.gpg | tar -xvzf -

This pattern avoids temporary plaintext files by streaming via STDIN/STDOUT.

Asymmetric encryption (public key)

If you’re sending data to someone else, encrypt to their public key so only they (with the private key) can decrypt:

# Encrypt to a recipient (use their email, key ID, or fingerprint)
tar -cvzf - /path/to/dir | gpg --encrypt --recipient [email protected] --output share.tar.gz.gpg

# Recipient decrypts and extracts
gpg --decrypt share.tar.gz.gpg | tar -xvzf -

If you don’t yet have keys: generate/import keys first, then use --recipient.

Listing contents without extracting

You can peek inside an encrypted archive:

gpg --decrypt secret.tar.gz.gpg | tar -tzf -

This decrypts to STDOUT and lists the tarball’s table of contents (-tzf) without writing files.

Notes & tips

  • Compression choices: swap -z (gzip) for -j (bzip2) or -J (xz) to trade speed vs. ratio.
  • File extensions: pick something descriptive, e.g. .tar.gz.gpg.
  • No intermediates: the pipe (|) keeps plaintext off disk during creation and decryption.
  • Alternative tool: gpgtar bundles archiving and GPG in one command if you prefer fewer moving parts.

Common pitfalls

  • Wrong recipient or missing key: ensure you imported/selected the correct public key before --encrypt.
  • Passphrase prompts in scripts: for unattended scripts, look into gpg --batch and pinentry options—handle secrets carefully.
This entry was posted in Guides, Linux, Security. Bookmark the permalink.

Leave a Reply