terminal-logo-small

GNU Privacy Guard (GnuPG or GPG) is a free software alternative to the PGP suite of cryptographic software. This is quick guide, howto Encrypt and Decrypt files on Linux with password using GPG.

This guide deals with both the interactive mode and the non interactive mode. Interactive mode is useful when the purpose is encrypt some files on the command line. Non interactive mode is useful when the purpose is encrypt files using scripts. This guide also deals with single file encryption/decryption and multiple files encryption/decryption simultaneously.

Linux Encrypt/Decrypt File on Linux using GPG

Encrypt File on Linux using GPG

Interactive Mode

gpg -c filename.txt 
## OR ## 
gpg --symmetric filename.txt

Enter passphrase: [Enter your passphrase here]
Repeat passphrase: [Repeat your passphrase here]

## First run output ##
gpg: directory '/home/username/.gnupg' created
gpg: new configuration file '/home/username/.gnupg/gpg.conf' created
gpg: WARNING: options in '/home/username/.gnupg/gpg.conf' are not yet active during this run
gpg: keyring '/home/username/.gnupg/pubring.gpg' created
Enter passphrase: [Enter your passphrase here]
Repeat passphrase: [Repeat your passphrase here]

Non Interactive Mode

gpg --yes --batch --passphrase=[Enter your passphrase here] -c filename.txt

Decrypt File on Linux using GPG

Interactive Mode

gpg filename.txt.gpg 

gpg: CAST5 encrypted data
Enter passphrase: [Enter your passphrase here]
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected

## First run output ##
gpg: keyring '/home/username/.gnupg/secring.gpg' created
gpg: CAST5 encrypted data
Enter passphrase: [Enter your passphrase here]
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected

Note: If file already exists then you get following info when decrypt file

File 'filename.txt' exists. Overwrite? (y/N) y

Non Interactive Mode

gpg --yes --batch --passphrase=[Enter your passphrase here] filename.txt.gpg

Quick Example Howto Use GPG on Command Line (Bash) Scripts

Following example is really simple backup from just created directory and files. Then script encrypts tar.gz package and remove original tar.gz file. After encryption file is safe to copy example to another server via FTP or so.

#!/bin/bash

BACKUP_DIR=/tmp/example-backup-dir
OUTPUT_FILE=/tmp/example-backup-dir.tar.gz
PASSPHRASE=my_secret_password

if [ -d $BACKUP_DIR ]; then
        rm -r $BACKUP_DIR
fi

mkdir $BACKUP_DIR

for i in {1..5}
do
   echo "Testing $i" > $BACKUP_DIR/file-$i.txt
done

tar -pczf $OUTPUT_FILE $BACKUP_DIR

gpg --yes --batch --passphrase=$PASSPHRASE -c $OUTPUT_FILE

rm $OUTPUT_FILE