Skip to content

Instantly share code, notes, and snippets.

@araujo88
Created February 28, 2024 03:31
Show Gist options
  • Save araujo88/73d5ce4caded953492d68d7cfcdc2268 to your computer and use it in GitHub Desktop.
Save araujo88/73d5ce4caded953492d68d7cfcdc2268 to your computer and use it in GitHub Desktop.
Encrypt a file with tar in Linux

To encrypt a file using tar in Linux, you generally combine tar with an encryption tool such as gpg (GNU Privacy Guard). This process involves creating a tarball of the files you wish to encrypt and then encrypting that tarball using gpg. Here is a step-by-step guide on how to do it:

Step 1: Install GPG

First, ensure that gpg is installed on your system. You can install it using your distribution's package manager if it's not already installed.

  • For Debian-based systems (like Ubuntu), use:
    sudo apt-get update
    sudo apt-get install gnupg
    
  • For Red Hat-based systems (like Fedora or CentOS), use:
    sudo dnf install gnupg
    
  • For Arch Linux:
    sudo pacman -S gnupg
    

Step 2: Create a Tarball

Next, create a tarball (.tar file) of the directory or files you wish to encrypt. Replace your-directory with the name of your directory or file.

tar -cvf archive-name.tar your-directory

This command creates a tarball named archive-name.tar containing your-directory.

Step 3: Encrypt the Tarball with GPG

Now, encrypt the tarball using gpg with encryption. You can encrypt it for a specific recipient (using their public key) or with a symmetric cipher (using a passphrase). Here's how to do it using a passphrase:

gpg -c archive-name.tar

You'll be prompted to enter a passphrase. Make sure to choose a strong passphrase and remember it, as you'll need it to decrypt the file later. This command creates an encrypted file named archive-name.tar.gpg.

Optional: Encrypt for a Specific Recipient

If you want to encrypt the file for a specific recipient, use the following command instead, replacing recipient@example.com with the email address associated with the recipient's public key:

gpg -e -r recipient@example.com archive-name.tar

This approach requires that you have the recipient's public key in your gpg keyring.

Step 4: Clean Up (Optional)

After encrypting the tarball, you may want to securely delete the unencrypted tarball to ensure that it cannot be recovered:

shred -u archive-name.tar

Or simply delete it if you're not worried about the data being recovered:

rm archive-name.tar

Decrypting the File

To decrypt the file, use the following command:

gpg -d archive-name.tar.gpg > decrypted-archive-name.tar

You'll be prompted to enter the passphrase. After decryption, you can untar the file using:

tar -xvf decrypted-archive-name.tar

This process allows you to securely encrypt and decrypt files using tar and gpg on Linux.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment