Docs / Security / How to Use GPG for File Encryption and Signing

How to Use GPG for File Encryption and Signing

By Admin · Mar 15, 2026 · Updated Apr 24, 2026 · 207 views · 2 min read

GPG (GNU Privacy Guard) is a free implementation of the OpenPGP standard for encrypting files, signing data, and managing cryptographic keys. It is essential for encrypting backups, verifying software authenticity, and secure file transfer.

Key Generation

# Generate a new GPG key pair
gpg --full-generate-key
# Choose: RSA and RSA
# Key size: 4096
# Expiry: 2y (recommended)
# Enter your name and email

# List your keys
gpg --list-keys
gpg --list-secret-keys

# Export your public key (share with others)
gpg --armor --export your@email.com > publickey.asc

# Export your private key (backup securely!)
gpg --armor --export-secret-keys your@email.com > privatekey.asc

Encrypting Files

# Encrypt for a specific recipient
gpg --encrypt --recipient recipient@email.com secret.txt
# Creates secret.txt.gpg

# Encrypt with symmetric password (no keys needed)
gpg --symmetric --cipher-algo AES256 backup.tar.gz
# Creates backup.tar.gz.gpg (prompts for password)

# Decrypt
gpg --decrypt secret.txt.gpg > secret.txt
gpg --decrypt backup.tar.gz.gpg > backup.tar.gz

Signing Files

# Create a detached signature
gpg --detach-sign --armor document.pdf
# Creates document.pdf.asc

# Verify a signature
gpg --verify document.pdf.asc document.pdf
# Good signature from "Your Name "

# Sign and encrypt in one step
gpg --sign --encrypt --recipient recipient@email.com document.pdf

Encrypting Backups

#!/bin/bash
# Encrypted backup script
DATE=$(date +%Y%m%d)
BACKUP_DIR="/var/backups"
GPG_RECIPIENT="backup@example.com"

# Create backup
mysqldump --all-databases | gzip > /tmp/db-${DATE}.sql.gz

# Encrypt with GPG
gpg --encrypt --recipient ${GPG_RECIPIENT} --trust-model always \
  /tmp/db-${DATE}.sql.gz

# Move encrypted backup
mv /tmp/db-${DATE}.sql.gz.gpg ${BACKUP_DIR}/

# Remove unencrypted file
rm /tmp/db-${DATE}.sql.gz

echo "Encrypted backup: ${BACKUP_DIR}/db-${DATE}.sql.gz.gpg"

Key Management

# Import someone else's public key
gpg --import theirkey.asc

# Trust a key (after verifying fingerprint)
gpg --edit-key their@email.com
# Type: trust
# Select trust level: 5 (ultimate) for your own keys, 4 (full) for verified contacts

# Revoke a compromised key
gpg --gen-revoke your@email.com > revocation.asc
# Store this securely — use it if your key is ever compromised

# Delete a key
gpg --delete-keys their@email.com
gpg --delete-secret-keys your@email.com

Best Practices

  1. Use 4096-bit RSA or Ed25519 keys
  2. Set an expiration date (1-2 years) and extend as needed
  3. Back up your private key and revocation certificate securely
  4. Use a strong passphrase on your private key
  5. Verify key fingerprints before trusting imported keys

Was this article helpful?