GPG/PGP Commands Reference
Overview
GPG (GNU Privacy Guard) is a free implementation of the OpenPGP standard (RFC 4880) for encrypting and signing data. It provides cryptographic privacy and authentication for data communication through public-key cryptography.
GPG is commonly used for:
- Email encryption - Secure email communication
- File encryption - Protect sensitive files
- Digital signatures - Verify authenticity and integrity
- Software distribution - Sign releases and verify downloads
- Password management - Encrypt password stores
- Git commit signing - Verify code authorship
Installation
macOS
# Using Homebrew
brew install gnupg
# Using MacPorts
sudo port install gnupg2
# Verify installation
gpg --versionLinux
# Debian/Ubuntu
sudo apt-get update
sudo apt-get install gnupg
# RHEL/CentOS/Fedora
sudo yum install gnupg2
# Arch Linux
sudo pacman -S gnupg
# Verify installation
gpg --versionWindows
# Download Gpg4win from: https://gpg4win.org/
# Or use Chocolatey
choco install gnupg
# Verify installation
gpg --versionKey Generation
Generate a New Key Pair
# Interactive key generation (recommended for beginners)
gpg --full-generate-key
# Quick key generation with defaults
gpg --generate-key
# Generate key with specific parameters
gpg --batch --generate-key <<EOF
%no-protection
Key-Type: RSA
Key-Length: 4096
Subkey-Type: RSA
Subkey-Length: 4096
Name-Real: John Doe
Name-Email: [email protected]
Expire-Date: 2y
EOFGenerate Key with Advanced Options
# Generate with ECC (Elliptic Curve Cryptography)
gpg --expert --full-generate-key
# Choose: (9) ECC (sign and encrypt)
# Choose curve: (1) Curve 25519
# Generate key with photo ID
gpg --edit-key [email protected]
gpg> addphoto /path/to/photo.jpg
gpg> saveGenerate Revocation Certificate
# Generate revocation certificate (create immediately after key generation)
gpg --output revoke.asc --gen-revoke [email protected]
# Store securely - this can revoke your key if compromisedKey Management
List Keys
# List public keys
gpg --list-keys
gpg -k
# List secret (private) keys
gpg --list-secret-keys
gpg -K
# List keys with fingerprints
gpg --fingerprint
# List keys with signatures
gpg --list-sigs
# List keys in machine-readable format
gpg --with-colons --list-keysExport Keys
# Export public key (ASCII armored)
gpg --armor --export [email protected] > public-key.asc
# Export public key (binary)
gpg --export [email protected] > public-key.gpg
# Export all public keys
gpg --armor --export > all-public-keys.asc
# Export secret key (KEEP SECURE!)
gpg --armor --export-secret-keys [email protected] > secret-key.asc
# Export secret subkeys only
gpg --armor --export-secret-subkeys [email protected] > secret-subkeys.asc
# Export specific key by fingerprint
gpg --armor --export A1B2C3D4E5F6 > specific-key.ascImport Keys
# Import public key from file
gpg --import public-key.asc
# Import from keyserver
gpg --keyserver keys.openpgp.org --recv-keys A1B2C3D4E5F6
# Import from clipboard (macOS)
pbpaste | gpg --import
# Import from clipboard (Linux)
xclip -o | gpg --import
# Import and trust key automatically (use with caution)
gpg --import public-key.asc
echo -e "5\ny\n" | gpg --command-fd 0 --expert --edit-key [email protected] trustDelete Keys
# Delete public key
gpg --delete-keys [email protected]
# Delete secret key (must delete public key first)
gpg --delete-secret-keys [email protected]
# Delete both secret and public keys
gpg --delete-secret-and-public-keys [email protected]
# Delete key without confirmation (use with caution)
gpg --batch --yes --delete-keys [email protected]Edit Keys
# Enter key edit mode
gpg --edit-key [email protected]
# Common edit commands:
# adduid - Add a user ID
# deluid - Delete a user ID
# addkey - Add a subkey
# delkey - Delete a subkey
# expire - Change expiration date
# trust - Change trust level
# passwd - Change passphrase
# revkey - Revoke a subkey
# enable/disable - Enable/disable a key
# save - Save and exit
# quit - Exit without saving
# Example: Change expiration date
gpg --edit-key [email protected]
gpg> expire
gpg> saveEncryption and Decryption
Encrypt Files
# Encrypt file for recipient (ASCII armored)
gpg --armor --encrypt --recipient [email protected] document.txt
# Encrypt file (binary output)
gpg --encrypt --recipient [email protected] document.txt
# Encrypt for multiple recipients
gpg --encrypt \
--recipient [email protected] \
--recipient [email protected] \
document.txt
# Encrypt and sign
gpg --encrypt --sign --recipient [email protected] document.txt
# Symmetric encryption (password-based, no keys required)
gpg --symmetric document.txt
gpg --armor --symmetric document.txt
# Encrypt with specific cipher
gpg --cipher-algo AES256 --encrypt --recipient [email protected] document.txtDecrypt Files
# Decrypt file
gpg --decrypt document.txt.gpg > document.txt
# Decrypt to specific output file
gpg --output document.txt --decrypt document.txt.gpg
# Decrypt and verify signature
gpg --decrypt document.txt.gpg
# Decrypt without writing to disk (view only)
gpg --decrypt document.txt.gpg | less
# Batch decrypt (no passphrase prompt)
gpg --batch --passphrase "your-passphrase" --decrypt document.txt.gpgEncrypt Messages
# Encrypt message from stdin
echo "Secret message" | gpg --armor --encrypt --recipient [email protected]
# Encrypt message and copy to clipboard (macOS)
echo "Secret message" | gpg --armor --encrypt --recipient [email protected] | pbcopy
# Encrypt message and copy to clipboard (Linux)
echo "Secret message" | gpg --armor --encrypt --recipient [email protected] | xclip -selection clipboard
# Decrypt message from clipboard (macOS)
pbpaste | gpg --decrypt
# Decrypt message from clipboard (Linux)
xclip -o | gpg --decryptSigning and Verification
Sign Files
# Create detached signature (recommended for software distribution)
gpg --detach-sign document.txt
# Creates: document.txt.sig
# Create detached signature (ASCII armored)
gpg --armor --detach-sign document.txt
# Creates: document.txt.asc
# Create clear-sign (signature inline with readable text)
gpg --clear-sign document.txt
# Creates: document.txt.asc
# Create binary signature (signature embedded in file)
gpg --sign document.txt
# Creates: document.txt.gpg
# Sign with specific key
gpg --local-user [email protected] --detach-sign document.txt
# Sign multiple files
gpg --detach-sign file1.txt file2.txt file3.txtVerify Signatures
# Verify detached signature
gpg --verify document.txt.sig document.txt
# Verify signature (ASCII armored)
gpg --verify document.txt.asc document.txt
# Verify clear-signed document
gpg --verify document.txt.asc
# Verify binary signed file
gpg --verify document.txt.gpg
# Verify and extract original file
gpg --output document.txt --decrypt document.txt.gpg
# Verify with specific keyring
gpg --keyring /path/to/keyring.gpg --verify document.txt.sig document.txtSign Git Commits
# Configure Git to use GPG
git config --global user.signingkey A1B2C3D4E5F6
git config --global commit.gpgsign true
git config --global tag.gpgsign true
# Sign a commit
git commit -S -m "Signed commit message"
# Sign a tag
git tag -s v1.0.0 -m "Signed tag"
# Verify commit signatures
git log --show-signature
# Verify tag signature
git tag -v v1.0.0
# Export public key for GitHub
gpg --armor --export [email protected]
# Paste into GitHub Settings > SSH and GPG keysKeyserver Operations
Upload Keys to Keyserver
# Upload to default keyserver
gpg --send-keys A1B2C3D4E5F6
# Upload to specific keyserver
gpg --keyserver keys.openpgp.org --send-keys A1B2C3D4E5F6
# Popular keyservers:
# keys.openpgp.org (recommended, verifies email)
# keyserver.ubuntu.com
# pgp.mit.edu
# keys.gnupg.netSearch and Retrieve Keys
# Search for key by email
gpg --keyserver keys.openpgp.org --search-keys [email protected]
# Search for key by name
gpg --keyserver keys.openpgp.org --search-keys "John Doe"
# Retrieve key by fingerprint
gpg --keyserver keys.openpgp.org --recv-keys A1B2C3D4E5F6
# Refresh keys from keyserver (check for revocations/updates)
gpg --refresh-keys
# Refresh specific key
gpg --keyserver keys.openpgp.org --refresh-keys A1B2C3D4E5F6Configure Default Keyserver
# Edit ~/.gnupg/gpg.conf
keyserver hkps://keys.openpgp.org
keyserver-options auto-key-retrieve
keyserver-options include-revoked
# Or use command line
echo "keyserver hkps://keys.openpgp.org" >> ~/.gnupg/gpg.confTrust and Web of Trust
Set Key Trust Level
# Edit key trust
gpg --edit-key [email protected]
gpg> trust
# Trust levels:
# 1 = I don't know or won't say
# 2 = I do NOT trust
# 3 = I trust marginally
# 4 = I trust fully
# 5 = I trust ultimately (own keys only)
gpg> 5
gpg> saveSign Keys (Web of Trust)
# Sign someone's key after verifying their identity
gpg --sign-key [email protected]
# Sign with specific trust level
gpg --edit-key [email protected]
gpg> sign
gpg> save
# Create a local (non-exportable) signature
gpg --lsign-key [email protected]
# Sign and upload to keyserver
gpg --sign-key [email protected]
gpg --send-keys A1B2C3D4E5F6Check Trust Path
# Check trust path to a key
gpg --check-trustdb
# List key signatures (show who signed the key)
gpg --list-sigs [email protected]
# Update trust database
gpg --update-trustdb
# Export ownertrust
gpg --export-ownertrust > ownertrust.txt
# Import ownertrust
gpg --import-ownertrust < ownertrust.txtAdvanced Operations
Backup and Restore
# Backup entire keyring
tar -czf gnupg-backup.tar.gz ~/.gnupg/
# Backup specific key with subkeys
gpg --armor --export-secret-keys [email protected] > private-keys.asc
gpg --armor --export-secret-subkeys [email protected] > private-subkeys.asc
gpg --armor --export [email protected] > public-keys.asc
gpg --export-ownertrust > trust.txt
# Restore keys
gpg --import private-keys.asc
gpg --import public-keys.asc
gpg --import-ownertrust < trust.txt
# Store backup securely offline (USB drive, encrypted volume)Key Rotation
# Generate new subkey for encryption
gpg --edit-key [email protected]
gpg> addkey
# Select: (6) RSA (encrypt only)
gpg> save
# Revoke old subkey
gpg --edit-key [email protected]
gpg> key 1 # Select subkey number
gpg> revkey
gpg> save
# Publish updated key
gpg --send-keys A1B2C3D4E5F6Smart Card Operations
# Check smart card status
gpg --card-status
# Edit smart card
gpg --card-edit
gpg/card> admin
gpg/card> passwd # Change PIN
gpg/card> name # Set cardholder name
gpg/card> url # Set public key URL
# Move key to smart card (Yubikey, etc.)
gpg --edit-key [email protected]
gpg> keytocard
gpg> saveBatch Operations
# Encrypt multiple files
for file in *.txt; do
gpg --encrypt --recipient [email protected] "$file"
done
# Decrypt multiple files
for file in *.gpg; do
gpg --decrypt "$file" > "${file%.gpg}"
done
# Verify multiple signatures
for sig in *.sig; do
gpg --verify "$sig" "${sig%.sig}"
done
# Sign multiple files
find . -type f -name "*.txt" -exec gpg --detach-sign {} \;Configuration
Common gpg.conf Settings
# ~/.gnupg/gpg.conf
# Use stronger key preferences
personal-cipher-preferences AES256 AES192 AES
personal-digest-preferences SHA512 SHA384 SHA256
personal-compress-preferences ZLIB BZIP2 ZIP Uncompressed
# Default key for signing
default-key A1B2C3D4E5F6
# Always use long key IDs
keyid-format 0xlong
# Show fingerprints
with-fingerprint
# Don't include version in output
no-emit-version
# Don't include comments in output
no-comments
# Use GPG agent for passphrase caching
use-agent
# Keyserver configuration
keyserver hkps://keys.openpgp.org
keyserver-options auto-key-retrieve
keyserver-options include-revoked
# Display photo IDs
list-options show-photos
verify-options show-photosgpg-agent Configuration
# ~/.gnupg/gpg-agent.conf
# Cache passphrases for 1 hour
default-cache-ttl 3600
max-cache-ttl 86400
# Enable SSH support (use GPG for SSH authentication)
enable-ssh-support
# Set pinentry program
pinentry-program /usr/local/bin/pinentry-mac
# Restart gpg-agent
gpgconf --kill gpg-agent
gpg-agent --daemonCommon Use Cases
Secure Email Communication
# Encrypt email message
gpg --armor --encrypt --sign --recipient [email protected] email.txt
# Decrypt received email
gpg --decrypt encrypted-email.asc
# Integration with email clients:
# - Thunderbird: Use Enigmail or built-in OpenPGP support
# - Apple Mail: Use GPGTools
# - Outlook: Use Gpg4win
# - Mutt: Built-in GPG supportPassword Management with pass
# Install pass (password-store)
brew install pass # macOS
apt-get install pass # Linux
# Initialize password store
pass init [email protected]
# Store a password
pass insert email/gmail
# Retrieve a password
pass email/gmail
# Generate a random password
pass generate email/gmail 20
# List all passwords
pass
# Remove a password
pass rm email/gmailEncrypt Directory
# Create encrypted tarball
tar -czf - /path/to/directory | gpg --encrypt --recipient [email protected] > directory.tar.gz.gpg
# Decrypt and extract
gpg --decrypt directory.tar.gz.gpg | tar -xzf -
# Alternative: encrypt individual files
find /path/to/directory -type f -exec gpg --encrypt --recipient [email protected] {} \;
find /path/to/directory -type f -name "*.gpg" -exec gpg --decrypt {} > {}.decrypted \;Verify Software Downloads
# Download software and signature
wget https://example.com/software.tar.gz
wget https://example.com/software.tar.gz.asc
# Import developer's public key
gpg --keyserver keys.openpgp.org --recv-keys DEVELOPER_KEY_ID
# Verify signature
gpg --verify software.tar.gz.asc software.tar.gz
# Expected output:
# gpg: Good signature from "Developer Name <[email protected]>"
# gpg: WARNING: This key is not certified with a trusted signature!
# Sign the key if you trust it
gpg --sign-key DEVELOPER_KEY_IDTroubleshooting
Common Issues
gpg: decryption failed: No secret key
Cause: Don't have the private key needed to decrypt.
Solution:
# Check if you have the private key
gpg --list-secret-keys
# Import private key if available
gpg --import private-key.asc
# Verify the file was encrypted for your key
gpg --list-packets encrypted-file.gpggpg: signing failed: Inappropriate ioctl for device
Cause: GPG can't prompt for passphrase.
Solution:
# Set GPG_TTY environment variable
export GPG_TTY=$(tty)
# Add to ~/.bashrc or ~/.zshrc
echo 'export GPG_TTY=$(tty)' >> ~/.bashrc
# Restart gpg-agent
gpgconf --kill gpg-agentgpg: public key not found
Cause: Missing recipient's public key.
Solution:
# Import from keyserver
gpg --keyserver keys.openpgp.org --search-keys [email protected]
# Import from file
gpg --import public-key.asc
# Verify key import
gpg --list-keys [email protected]gpg: WARNING: This key is not certified with a trusted signature
Cause: Key hasn't been signed by a trusted key.
Solution:
# This is normal for newly imported keys
# Verify key fingerprint through alternate channel (phone, in person)
gpg --fingerprint [email protected]
# If verified, sign the key
gpg --sign-key [email protected]
# Or set ultimate trust (only for your own keys)
gpg --edit-key [email protected]
gpg> trust
gpg> 5
gpg> savegpg-agent not responding
Cause: gpg-agent daemon crashed or not running.
Solution:
# Kill and restart gpg-agent
gpgconf --kill gpg-agent
gpg-agent --daemon
# Check gpg-agent status
gpg-agent --version
echo GETINFO version | gpg-connect-agent
# Check socket permissions
ls -la ~/.gnupg/S.gpg-agentKeyserver timeout or unavailable
Cause: Keyserver down or network issues.
Solution:
# Try different keyserver
gpg --keyserver keyserver.ubuntu.com --recv-keys KEY_ID
# Use HTTP instead of HTTPS
gpg --keyserver hkp://keys.openpgp.org --recv-keys KEY_ID
# Import key from file instead
wget https://example.com/public-key.asc
gpg --import public-key.ascDebugging Commands
# Enable verbose output
gpg --verbose --decrypt file.gpg
# Enable debug output
gpg --debug-all --decrypt file.gpg
# Check GPG configuration
gpg --version
gpg --list-config
# Test keyserver connectivity
gpg --keyserver keys.openpgp.org --recv-keys 0x0000000000000000
# Check permissions
ls -la ~/.gnupg/
chmod 700 ~/.gnupg
chmod 600 ~/.gnupg/*
# Verify gpg-agent socket
gpg-connect-agent /byeBest Practices
Key Management
- Use 4096-bit RSA keys - Better security than 2048-bit
- Set key expiration - 2-5 years recommended, forces key rotation
- Generate revocation certificate immediately - Store securely offline
- Backup private keys - Store encrypted backup offline
- Use subkeys - Keep master key offline, use subkeys for daily operations
- Publish to keyservers - Makes public key discoverable
- Add multiple UIDs - Include all email addresses you use
Operational Security
- Never share private keys - Private keys should never leave your device
- Use strong passphrases - Protect private keys with strong passphrases
- Verify fingerprints - Always verify key fingerprints through alternate channels
- Sign keys carefully - Only sign keys after verifying owner identity
- Revoke compromised keys immediately - Use revocation certificate if key compromised
- Keep software updated - Regularly update GPG to latest version
- Use hardware tokens - Consider Yubikey or other smart cards for key storage
Encryption Practices
- Always sign encrypted messages - Prevents impersonation attacks
- Encrypt to yourself - Include your own key to decrypt later
- Verify signatures - Always check signatures on received messages
- Use ASCII armor for email - Binary format may be corrupted by email systems
- Avoid symmetric encryption for sharing - Public key encryption is more secure
- Delete decrypted files securely - Use secure deletion tools (shred, srm)
Key Distribution
- Publish to multiple keyservers - Ensures availability
- Include key fingerprint in email signature - Makes verification easier
- Publish on personal website/GitHub - Additional distribution channel
- Verify key ownership - Use Web Key Directory (WKD) or DANE
- Participate in key signing parties - Build web of trust
Related Tools
- OpenSSL Commands - X.509 certificates and SSL/TLS
- SSH Commands - SSH key management and authentication (use ssh-keygen for key operations)
- pass - Password manager built on GPG
- Keybase - Modern GPG with social verification
- Kleopatra - GUI certificate manager (Gpg4win)
- GPGTools - GPG Suite for macOS
Additional Resources
- Official Documentation -
man gpgor gnupg.org/documentation - OpenPGP Standard - RFC 4880 specification
- Best Practices - Riseup OpenPGP Best Practices
- GPG Quick Start - GNU Privacy Handbook