Linux password protected tar.gz file

The problem

.tar, .gz and .tar.gz files cannot be password protected directly.

.zip files can be, but not really safe.

The Solution

Pipe tar command to gpg.

Tested enviroment

  • Ubuntu 18.04 with gpg package (apt install gpg).

The Code

Encrypt (asks for password):

tar czvf - directory | gpg --symmetric --cipher-algo aes256 -o directory.tar.gz.gpg

Decrypt:

gpg -d directory.tar.gz.gpg | tar xzvf -

References

Extras

Extra 1: simple bash scripts

tar_encrypt.sh:

#!/bin/bash
if [ ! "$1" ]; then
    echo ""
    echo "Tell me the target name (without extension, I'll do that for you)"
    echo "-----------------------------------------------------------------"
    echo "usage: tar_encrypt my_target_name directory/"
    echo ""
    exit 0
fi

if [ ! "$2" ]; then
    echo "Tell me directory/file to be processed"
    echo ""
    echo "usage: tar_encrypt my_target_name directory/"
    exit 0
fi

tar czvf - ${2} | gpg --symmetric --cipher-algo aes256 -o ${1}.tar.gz.gpg

tar_decrypt.sh

#!/bin/bash
if [ ! "$1" ]; then
    echo ""
    echo "Tell me the target name"
    echo "-----------------------"
    echo "usage: tar_decrypt my_target_name.tar.gz.gpg"
    echo ""
    exit 0
fi

gpg -d ${1} | tar xzvf -

Set them executable:

chmod 755 *.sh

Extra 2: password protected zip files

zip -er procteced.zip directory/

Where:

-r   recurse into directories
-e   encrypt