Secure tar and gzip Archives in Linux: Encrypt and Verify

Create secure tar.gz archives in Linux: umask, GPG encryption, checksums and signatures, safe extraction, ACL/SELinux preservation and a backup script.

Aug 1, 2025 - 19:23
Nov 6, 2026 - 14:24
 0  268
TOPICDevOps BasicsPractical guide
Secure tar and gzip Archives in Linux: Encrypt and Verify

tar and gzip on their own do not secure anything: they bundle and compress files, but anyone who gets the archive can read it. A secure archive adds four things: tight permissions on the file, encryption (usually GPG), a checksum or signature to prove it was not changed, and careful extraction so a hostile archive cannot overwrite system files.

This guide is part of our Linux basics series (start with RHEL 10 basic commands every beginner should know). It focuses on security. If you want to choose between gzip, bzip2 and xz for size or speed, read our separate comparison of gzip vs bzip2 vs xz.

Key takeaways

  • Set umask 077 before creating an archive so the file is readable only by you from the moment it exists.
  • Encrypt with GPG: symmetric (gpg -c, one passphrase) for personal backups, or public-key (gpg -e -r) when someone else or an automated restore must open it.
  • Never put a passphrase on the command line. Other users can see process arguments, and shells save history.
  • Publish or store a SHA-256 checksum, or a GPG signature, alongside the archive and verify it before restoring.
  • List an archive with tar -tvf before extracting it, extract untrusted archives as a normal user into an empty directory, and avoid -P.
  • Use -p, --acls, --xattrs and --selinux when you need permissions and security labels restored correctly.

What tar and gzip actually do

tar (tape archive) joins many files and directories into one stream and records each file's name, owner, group, mode and timestamps. gzip compresses that stream with the DEFLATE algorithm. GNU tar calls gzip for you with -z:

tar -czf project.tar.gz project/      # create
tar -tzf project.tar.gz               # list
tar -xzf project.tar.gz               # extract

Neither tool offers encryption or integrity protection. gzip does store a CRC-32 checksum, which catches accidental corruption, but anyone who changes the archive on purpose can recompute it. Security has to come from the steps around them.

The threats you are protecting against

ThreatExampleControl
Unauthorised readingA backup copied to a shared bucket or a lost laptopEncryption, file permissions
TamperingA release tarball replaced on a mirrorGPG signature or checksum from a trusted source
Secrets swept into the archive.env files, private keys, .git directories--exclude, review with tar -tvf
Path traversal on extractionA member named ../../etc/cron.d/jobGNU tar defaults, extract as non-root, inspect first
Wrong ownership after restoreFiles restored as root or with the wrong UID-p, --same-owner, --numeric-owner used deliberately
Silent corruptionBit rot on old mediaChecksums, regular test restores

Step 1: create the archive with safe permissions

The default umask on most systems (022) makes new files readable by everyone. Set a stricter umask in a subshell so it only affects this job:

( umask 077
  tar -czf /backup/app-$(date +%F).tar.gz \
      --exclude='*.key' --exclude='.env' --exclude='.git' \
      -C /srv app )
ls -l /backup/app-*.tar.gz        # should show -rw-------

-C /srv app stores paths as app/... rather than absolute paths, which makes restoring to another location easier. Keep the backup directory itself at mode 700. For more on modes, see chmod vs chown vs chgrp.

Before encrypting or shipping anything, review what went in:

tar -tvzf /backup/app-2026-11-07.tar.gz | less
tar -tzf /backup/app-2026-11-07.tar.gz | grep -Ei 'id_rsa|id_ed25519|\.pem$|\.env$|secret'

Step 2: encrypt with GPG

Symmetric encryption (one passphrase)

Good for personal or ad hoc backups. GPG prompts for the passphrase, so it never appears in your shell history:

tar -czf - -C /srv app | gpg --symmetric --cipher-algo AES256 -o app.tar.gz.gpg

Piping avoids writing an unencrypted archive to disk at all. To restore:

gpg -d app.tar.gz.gpg | tar -xzf - -C /restore

Current GnuPG versions already use AES for symmetric encryption by default and protect the data with an integrity check, so --cipher-algo AES256 mainly makes the choice explicit. If you lose the passphrase, the data cannot be recovered.

Public-key encryption (for automation and teams)

For scheduled backups, encrypt to a public key. The backup server holds only the public key, so a compromise of that server does not expose old archives. The private key stays offline or with the restore team.

# one time: import the recipient's public key and check its fingerprint
gpg --import backup-team.pub
gpg --fingerprint [email protected]

# each run
tar -czf - -C /srv app | gpg --encrypt --recipient [email protected] -o app-$(date +%F).tar.gz.gpg

No passphrase is needed to encrypt, which suits cron jobs. Combining this with rsync and cron is covered in automating backups with rsync and cron.

Other options

  • age is a small, modern file encryption tool with public-key and passphrase modes (tar -czf - dir | age -r RECIPIENT > dir.tar.gz.age). It is packaged by many distributions; check yours.
  • openssl enc can encrypt a stream, but it provides no integrity protection in that mode and needs options such as -pbkdf2 to derive keys properly. GPG or age is the simpler safe choice.
  • Avoid the old ZIP "password" encryption (ZipCrypto), which is considered weak.

Step 3: prove the archive was not changed

Encryption with GPG detects tampering when you decrypt, but you often want to check integrity first, or you are distributing an unencrypted archive such as a software release. Two methods:

Checksums

sha256sum app-2026-11-07.tar.gz.gpg > app-2026-11-07.tar.gz.gpg.sha256
sha256sum -c app-2026-11-07.tar.gz.gpg.sha256

A checksum only helps if the reader gets it from a source the attacker cannot also change. Store it separately, or sign it.

Detached GPG signature

gpg --armor --detach-sign app-2.4.1.tar.gz       # creates app-2.4.1.tar.gz.asc
gpg --verify app-2.4.1.tar.gz.asc app-2.4.1.tar.gz

A signature proves who produced the file, as long as the verifier trusts the signer's key fingerprint. This is how many open source projects publish release tarballs, and it is the check you should run before building software from source (see binary vs source package installation).

Step 4: extract safely

Extraction is the more dangerous half. An archive from an untrusted source can contain absolute paths, .. components or symbolic links aimed outside the target directory. GNU tar defends against the common cases by default: it strips a leading / from member names and refuses members whose names contain .., printing a warning. Keep those defenses on:

  • Do not use -P (--absolute-names) on archives you did not create. It turns those protections off.
  • List first: tar -tvf archive.tar.gz shows names, owners, modes and symlink targets.
  • Extract into a new empty directory with -C, as a normal user, not as root.
  • Use --one-top-level (GNU tar 1.28 and later) to force everything under one directory named after the archive.
  • Use --no-overwrite-dir and -k (--keep-old-files) if you must extract over existing data and want to avoid replacing files.
mkdir -p ~/inspect/vendor-drop
tar -tvzf vendor-drop.tar.gz | head -50
tar -xzf vendor-drop.tar.gz -C ~/inspect/vendor-drop --no-same-owner

When run by root, GNU tar restores the owners recorded in the archive by default. That is right for your own backups and wrong for third-party archives, where --no-same-owner (the default for normal users) is safer. Python's tarfile module added extraction filters for the same reason; if you write tooling in Python, use filter="data".

Preserving permissions, ACLs and SELinux labels

For system backups, you usually want the restore to match the original exactly:

# create
sudo tar --acls --xattrs --selinux -cpzf etc-$(date +%F).tar.gz -C / etc
# restore
sudo tar --acls --xattrs --selinux -xpzf etc-2026-11-07.tar.gz -C /
OptionWhat it doesWhen to use it
-pRestore exact permission bits on extract (default for root)System and application restores
--aclsStore and restore POSIX ACLsShared directories that use setfacl
--xattrsStore and restore extended attributesFiles with capabilities or other xattrs
--selinuxStore and restore SELinux contextsRHEL and Fedora system files
--numeric-ownerUse UID/GID numbers instead of namesRestoring to a system with different user names
--no-same-ownerExtracted files belong to the user running tarUntrusted or third-party archives

If SELinux labels end up wrong after a restore, restorecon -Rv /path resets them to the policy defaults. Our SELinux in RHEL 10 guide explains contexts.

A complete secure backup script

#!/usr/bin/env bash
set -euo pipefail
umask 077

SRC_PARENT=/srv
SRC_DIR=app
DEST=/backup
[email protected]
STAMP=$(date +%F)
OUT="$DEST/${SRC_DIR}-${STAMP}.tar.gz.gpg"

tar --acls --xattrs --selinux -cpzf - \
    --exclude='.git' --exclude='*.tmp' \
    -C "$SRC_PARENT" "$SRC_DIR" \
  | gpg --batch --yes --encrypt --recipient "$RECIPIENT" -o "$OUT"

sha256sum "$OUT" > "$OUT.sha256"

# keep 14 days
find "$DEST" -name "${SRC_DIR}-*.tar.gz.gpg*" -mtime +14 -delete

set -o pipefail makes the script fail if tar fails, not just gpg. Test a restore on another machine regularly; an encrypted backup that no one can decrypt is not a backup. Wider recovery planning is covered in the RHEL 10 backup and restore guide.

Common mistakes

  • Writing gpg --passphrase mysecret in a script. Use public-key encryption, or a passphrase file readable only by the backup user with --pinentry-mode loopback --passphrase-file.
  • Creating the plain archive first and encrypting it later, leaving an unencrypted copy on disk.
  • Storing the checksum next to the archive in the same writable location and calling it tamper-proof.
  • Extracting downloads as root straight into / or /opt.
  • Forgetting that tar keeps the original modes: a world-readable config file stays world-readable after restore.

Archiving, compression and permissions are listed in the Red Hat RHCSA objectives. The Linux administration course, in our Kharadi, Pune classroom and live online, covers these tasks in hands-on labs.

Frequently asked questions

Does gzip encrypt files?

No. gzip only compresses. Anyone can decompress a .gz file. To protect the contents, encrypt the archive with a tool such as GPG or age.

How do I password-protect a tar.gz file in Linux?

Pipe it through GPG symmetric encryption: tar -czf - folder | gpg -c -o folder.tar.gz.gpg. GPG asks for the passphrase. Decrypt with gpg -d folder.tar.gz.gpg | tar -xzf -.

Is it safe to extract any tar file?

Not as root and not blindly. List it first with tar -tvf, extract as a normal user into an empty directory, and avoid -P. GNU tar strips leading slashes and refuses .. paths by default, which blocks the most common path traversal tricks.

Does tar preserve file permissions?

tar always records permissions. When extracting, root restores them exactly by default; normal users get them filtered by their umask unless they add -p. Add --acls, --xattrs and --selinux to keep ACLs, extended attributes and SELinux labels.

Should I use symmetric or public-key encryption for backups?

Use public-key encryption for automated backups, because the server only needs the public key and no passphrase is stored. Symmetric encryption is fine for one-off archives you will open yourself.

How do I check that an archive has not been tampered with?

Compare its SHA-256 checksum with one obtained from a trusted place, or verify a detached GPG signature with gpg --verify file.asc file. A signature is stronger because it also proves who created the file.

Which compression should I use for secure archives?

Compression choice does not affect security. gzip is the most compatible; xz gives smaller files at higher CPU cost. Our gzip vs bzip2 vs xz comparison covers the trade-offs.

Why compress before encrypting?

Encrypted data looks random and does not compress, so compression has to happen first. GPG can also compress by itself, but piping a .tar.gz into GPG keeps the archive format familiar.

References

Interested in learning more?Get a callback from our training advisors.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.