Post

PGP Encryption Implementation Guide

In-depth guide to PGP encryption: generate and manage keys, encrypt and sign messages, integrate with email clients, and apply best practices for secure communication.

PGP Encryption Implementation Guide

Comprehensive Security Guide to PGP Implementation

1. Introduction and Purpose

Pretty Good Privacy (PGP) is a data encryption and decryption program that provides cryptographic privacy and authentication for data communication. Despite its “Pretty Good” name, when properly implemented, PGP offers strong security for protecting sensitive information, signing communications, and verifying sender authenticity.

This guide provides comprehensive instructions for securely implementing and using PGP across various environments, with special attention to security considerations at each step. Following these practices will help you avoid common pitfalls that can undermine PGP’s robust security model.

Key Security Benefits of PGP:

  • End-to-end encryption for confidential communications
  • Message integrity verification
  • Non-repudiation through digital signatures
  • Long-term protection of sensitive data
  • Identity verification through a web of trust

2. Table of Contents

  1. Introduction and Purpose
  2. Table of Contents
  3. Understanding PGP Technology
  4. Installation
  5. Key Management
  6. Configuration
  7. Daily Operations
  8. Security Best Practices
  9. Integrations
  10. Testing and Validation
  11. Troubleshooting
  12. References and Further Reading
  13. Appendices
  14. Change Log

3. Understanding PGP Technology

3.1 Core Concepts

PGP employs a hybrid cryptosystem that combines:

  • Symmetric encryption: Uses a single key to encrypt large amounts of data efficiently
  • Asymmetric encryption: Uses public/private key pairs for key exchange and digital signatures
  • Hash functions: Ensures data integrity
  • Compression: Reduces encrypted data size and improves security

3.2 The PGP Encryption Process

  1. Data is compressed to reduce transmission time and strengthen cryptographic security
  2. A one-time random symmetric key (session key) is generated
  3. The data is encrypted using the symmetric key
  4. The symmetric key is encrypted using the recipient’s public key
  5. The encrypted symmetric key is attached to the encrypted data

3.3 GNU Privacy Guard (GnuPG/GPG)

GnuPG is the most widely used free implementation of the OpenPGP standard defined by RFC 4880. When this guide refers to PGP, we are generally referring to the OpenPGP standard as implemented by GnuPG.

4. Installation

4.1 Linux Installation

Debian/Ubuntu

1
2
3
4
5
# Install GnuPG
sudo apt update
sudo apt install gnupg2
# Verify installation
gpg --version

Red Hat/Fedora/CentOS

1
2
3
4
# Install GnuPG
sudo dnf install gnupg2
# Verify installation
gpg --version

Security considerations:

  • Always verify the package signature before installation
  • Use distribution package managers rather than manual installation when possible
  • Ensure you’re installing from official repositories

4.2 macOS Installation

1
2
3
4
5
6
# Install Homebrew if not already installed
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install GnuPG
brew install gnupg
# Verify installation
gpg --version

Using GPG Suite (GUI option)

  1. Download GPG Suite from gpgtools.org
  2. Verify the download using the provided checksums:
1
2
3
# Example checksum verification
shasum -a 256 GPG_Suite-2023.1.dmg
# Compare with checksum on website
  1. Mount the disk image and run the installer

4.3 Windows Installation

Using Gpg4win

  1. Download Gpg4win from gpg4win.org
  2. Verify the installer signature:
1
2
3
4
5
6
# Download the signature file
Invoke-WebRequest -Uri "https://gpg4win.org/package-signing-key.asc" -OutFile "gpg4win-key.asc"
# Import the key
gpg --import gpg4win-key.asc
# Verify the signature
gpg --verify Gpg4win-3.1.16.exe.sig Gpg4win-3.1.16.exe
  1. Run the installer with default components (at minimum, GnuPG and Kleopatra)

4.4 Docker/Container Installation

For ephemeral environments or CI/CD pipelines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
FROM ubuntu:22.04

RUN apt-get update && \
    apt-get install -y gnupg2 && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# Create a dedicated user for running GPG operations
RUN useradd -m gpguser
USER gpguser
WORKDIR /home/gpguser

# Initialize GPG home directory with secure permissions
RUN mkdir -p ~/.gnupg && \
    chmod 700 ~/.gnupg

# Configure GPG to use more secure algorithms by default
RUN echo "cert-digest-algo SHA512" > ~/.gnupg/gpg.conf && \
    echo "default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed" >> ~/.gnupg/gpg.conf

ENTRYPOINT ["gpg"]

4.5 Verification

After installation, verify that you are using a recent version of GnuPG with strong algorithms:

1
gpg --version

Ensure the version is 2.2.x or newer and that it lists strong algorithms such as:

  • Ciphers: AES256, AES192, AES
  • Hashes: SHA512, SHA384, SHA256
  • Compression: ZLIB, BZIP2, ZIP

5. Key Management

5.1 Key Generation

5.1.1 Secure Key Creation

1
2
# Interactive key generation with modern defaults
gpg --full-generate-key

When prompted:

  1. Select key type: (1) RSA and RSA (default)
  2. Key size: 4096 bits (stronger than default)
  3. Validity period: 2 years (balance between security and convenience)
  4. User ID information: Your real name and email address
  5. Create a strong passphrase (see section 5.1.3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Non-interactive key generation with explicit security parameters
gpg --batch --gen-key <<EOF
Key-Type: RSA
Key-Length: 4096
Subkey-Type: RSA
Subkey-Length: 4096
Name-Real: Your Full Name
Name-Email: [email protected]
Expire-Date: 2y
Passphrase: your-secure-passphrase
# Add a comment to identify the key purpose
Name-Comment: work encryption key
# Do not generate a key without a passphrase
%no-protection
# Ensure key characteristics are not auto-adjusted without consent
%no-ask-passphrase
%commit
EOF

5.1.3 Passphrase Guidelines

Create a strong passphrase that:

  • Is at least 16 characters long
  • Contains a mix of uppercase, lowercase, numbers, and symbols
  • Avoids dictionary words, names, and predictable patterns
  • Is memorable enough that you won’t need to write it down
  • Is unique (not reused for other services)

Consider using a password manager to generate and store the passphrase.

5.2 Key Backup

5.2.1 Exporting Keys

1
2
3
4
5
# Export public key
gpg --export --armor [email protected] > public_key.asc

# Export private key (store this securely!)
gpg --export-secret-keys --armor [email protected] > private_key.asc

5.2.2 Secure Storage Options

For private key backups:

  • Encrypted USB drive kept in a physically secure location
  • Password-protected encrypted archive on secure cloud storage
  • Paper backup (printout) stored in a safe
  • Hardware security device like YubiKey or Nitrokey

For maximum security, split the key using Shamir’s Secret Sharing:

1
2
# Using ssss-split utility (install ssss package first)
ssss-split -t 3 -n 5 < private_key.asc > key_shares.txt

This creates 5 shares where any 3 can reconstruct the key.

5.3 Key Revocation

5.3.1 Creating a Revocation Certificate

Generate immediately after key creation:

1
gpg --output revocation_cert.asc --gen-revoke [email protected]

Store this certificate securely but separately from your private key.

5.3.2 Using a Revocation Certificate

If your key is compromised:

1
2
3
4
5
# Import revocation certificate
gpg --import revocation_cert.asc

# Send to keyservers
gpg --keyserver keys.openpgp.org --send-keys [YOUR_KEY_ID]

5.4 Key Rotation and Expiration

  • Set expiration dates on all keys (typically 1-2 years)
  • Create new keys before old ones expire
  • Overlap periods to ensure smooth transition
  • Sign new keys with old ones to maintain trust paths
1
2
3
4
5
6
7
8
# Check expiration dates
gpg --list-keys --with-colons [email protected] | grep "^pub"

# Extend expiration if needed
gpg --edit-key [email protected]
> expire
> 2y
> save

6. Configuration

6.1 Basic Configuration

Create or edit ~/.gnupg/gpg.conf with secure defaults:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Strong hash preferences
personal-digest-preferences SHA512 SHA384 SHA256
cert-digest-algo SHA512
default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed

# Prevent leaking information about keys
no-emit-version
no-comments
export-options export-minimal

# Display full fingerprints for better security
keyid-format 0xlong
with-fingerprint
with-subkey-fingerprint

# Always use strong cipher
cipher-algo AES256

# Enable verbose and accurate warnings
throw-keyids

6.2 Agent Configuration

Edit ~/.gnupg/gpg-agent.conf:

1
2
3
4
5
6
7
8
9
10
11
12
13
# Cache settings (adjust timeouts based on your security requirements)
default-cache-ttl 600
max-cache-ttl 1800

# Enforce passphrase complexity
min-passphrase-len 12
min-passphrase-nonalpha 3

# Enable ssh support if needed
enable-ssh-support

# Pinentry program selection
pinentry-program /usr/bin/pinentry-gtk-2

6.3 Common Misconfigurations to Avoid

  • Weak algorithms: Don’t use legacy algorithms like IDEA, 3DES, or SHA-1
  • Indefinite validity: Never create keys without expiration dates
  • Disabled encrypt-to-self: Always keep the encrypt-to-self option enabled
  • Excessive key sharing: Don’t upload private keys to shared storage
  • Inadequate permissions: Ensure ~/.gnupg directory has 700 permissions
  • Overly long cache duration: Don’t set extremely long cache timeouts

6.4 Role-Based Access Configuration

For organizations managing multiple users and keys:

1
2
3
4
5
6
# Create dedicated GNUPGHOME for specific roles
mkdir -p /etc/gpg-roles/finance
chmod 700 /etc/gpg-roles/finance

# Use role-specific configuration
GNUPGHOME=/etc/gpg-roles/finance gpg --gen-key

7. Daily Operations

7.1 Encrypting Files

1
2
3
4
5
6
7
8
# Encrypt file for recipient
gpg --encrypt --recipient [email protected] --output encrypted_file.gpg input_file.txt

# Encrypt and sign file
gpg --encrypt --sign --recipient [email protected] --output encrypted_signed_file.gpg input_file.txt

# Encrypt with password (symmetric encryption)
gpg --symmetric --cipher-algo AES256 --output encrypted_file.gpg input_file.txt

7.2 Decrypting Files

1
2
3
4
5
# Decrypt file
gpg --decrypt --output decrypted_file.txt encrypted_file.gpg

# Decrypt and verify signature
gpg --decrypt --output decrypted_file.txt encrypted_signed_file.gpg

7.3 Signing Files

1
2
3
4
5
# Create detached signature
gpg --detach-sign --output document.pdf.sig document.pdf

# Create clear-signed text file
gpg --clearsign --output signed_message.txt message.txt

7.4 Verifying Signatures

1
2
3
4
5
# Verify detached signature
gpg --verify document.pdf.sig document.pdf

# Verify clear-signed file
gpg --verify signed_message.txt

7.5 Managing Keys

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# List public keys
gpg --list-keys

# List private keys
gpg --list-secret-keys

# Import a key
gpg --import received_key.asc

# Export your public key to share
gpg --export --armor [email protected]

# Delete a key
gpg --delete-key [email protected]  # public key
gpg --delete-secret-key [email protected]  # private key

8. Security Best Practices

8.1 Hardening Techniques

8.1.1 Filesystem Security

1
2
3
4
# Set correct permissions for GnuPG home directory
chmod 700 ~/.gnupg
find ~/.gnupg -type f -exec chmod 600 {} \;
find ~/.gnupg -type d -exec chmod 700 {} \;

8.1.2 Secure Hardware Options

  • Hardware security keys: YubiKey, Nitrokey, or OpenPGP Card
  • Air-gapped systems: Maintain a separate, offline computer for key operations
  • Secure boot environments: Use Tails OS for sensitive key operations
1
2
3
4
# Configure GnuPG to use a hardware key
gpg --card-status
gpg --edit-key [email protected]
> keytocard

8.1.3 Enhanced Security Measures for High-Value Keys

  • Entropy augmentation: Use hardware random number generators
  • Side-channel protection: Use CPU isolation and memory protections
  • RAM clearing: Implement secure memory handling
1
2
# Use a hardware RNG if available (rng-tools must be installed)
sudo rngd -r /dev/hwrng

8.2 Secrets Management

8.2.1 Passphrase Handling

  • Use a password manager for generating and storing passphrases
  • Consider split knowledge procedures for critical keys (multiple partial passphrases)
  • Implement passphrase rotation policies

8.2.2 Private Key Security

  • Never store private keys on shared systems
  • Implement key recovery procedures before emergency scenarios
  • Use subkeys for day-to-day operations, keeping the master key offline
1
2
3
4
5
# Generate a subkey for everyday use
gpg --edit-key [email protected]
> addkey
# (follow prompts to create encryption subkey)
> save

8.3 Logging and Audit

Configure logging in ~/.gnupg/gpg.conf:

1
2
3
4
# Enable verbose logging
verbose
debug-level basic
log-file ~/.gnupg/gpg.log

For enterprise environments, forward logs to a SIEM:

1
2
3
# Set up log forwarding (using syslog as an example)
echo "*.* @siem-server.example.com:514" | sudo tee -a /etc/rsyslog.d/90-gnupg.conf
sudo systemctl restart rsyslog

8.4 Threat Modeling for PGP

ThreatImpactMitigation
Private key theftComplete compromise of encrypted dataHardware security keys, air-gapped key management
Weak passphraseUnauthorized key accessStrong passphrase policies, regular rotation
Man-in-the-middleImpersonation, encrypted comms with wrong recipientWeb of trust, fingerprint verification
Metadata leakageCommunication patterns exposedUse alongside anonymizing technologies (Tor)
Quantum computingFuture decryption of current communicationsKey size increases, algorithm agility, forward secrecy

8.5 Secure Update Procedures

  1. Verify signatures of GnuPG updates before installation
  2. Test updates in isolated environments first
  3. Maintain backups of working configurations
  4. Use package managers that validate signatures
  5. Subscribe to security announcements
1
2
3
4
# Example: verifying GnuPG release signature
wget https://gnupg.org/ftp/gcrypt/gnupg/gnupg-2.4.3.tar.bz2
wget https://gnupg.org/ftp/gcrypt/gnupg/gnupg-2.4.3.tar.bz2.sig
gpg --verify gnupg-2.4.3.tar.bz2.sig gnupg-2.4.3.tar.bz2

9. Integrations

9.1 Email Client Integration

9.1.1 Thunderbird with Enigmail

  1. Install Thunderbird
  2. Install the Enigmail add-on
  3. Configure Enigmail with your key:
    • Tools → Add-ons → Enigmail → Preferences
    • Select your key from the list or import it
    • Enable automatic encryption/signing as needed

Security considerations:

  • Disable HTML email to prevent side-channel leaks
  • Configure “Send Later” to prevent accidental unencrypted sends
  • Never auto-save drafts of sensitive emails

9.1.2 Command-line Email with Mutt

Configure ~/.muttrc:

1
2
3
4
5
6
7
8
9
# PGP configuration for Mutt
set pgp_use_gpg_agent = yes
set pgp_sign_as = "0xYOUR_KEY_ID"
set pgp_timeout = 600
set crypt_autosign = yes
set crypt_replyencrypt = yes
set crypt_replysign = yes
set crypt_replysignencrypted = yes
set crypt_verify_sig = yes

9.2 DevOps Integration

9.2.1 CI/CD Pipeline Secret Management

1
2
3
4
5
6
7
8
9
10
11
# Example GitLab CI configuration for PGP-encrypted secrets
stages:
  - deploy

decrypt_secrets:
  stage: deploy
  script:
    - echo "$CI_GPG_PRIVATE_KEY" | gpg --import
    - echo "$CI_GPG_PASSPHRASE" | gpg --batch --passphrase-fd 0 --decrypt secrets.gpg > secrets.yml
  only:
    - master

9.2.2 Git Commit Signing

Configure Git to use GPG for commit signing:

1
2
3
4
5
6
7
# Configure Git with your signing key
git config --global user.signingkey YOUR_KEY_ID
git config --global commit.gpgsign true

# Sign commits and tags
git commit -S -m "Signed commit message"
git tag -s v1.0 -m "Signed tag"

Verify signatures:

1
2
git verify-commit HEAD
git verify-tag v1.0

9.3 Integration with Password Managers

9.3.1 Pass - the Standard Unix Password Manager

1
2
3
4
5
6
7
8
9
10
11
# Initialize pass with your GPG key
pass init [email protected]

# Store a password
pass insert Email/work

# Generate and store a random password
pass generate Bank/online 20

# Retrieve a password
pass Email/work

9.3.2 Custom Integrations

Example shell function for secure file encryption:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
encrypt_for_team() {
  local file=$1
  local output=${2:-"$file.gpg"}
  
  # List of team member key IDs
  local team_keys=("0xABC123" "0xDEF456" "0xGHI789")
  
  # Build recipient list
  local recipients=""
  for key in "${team_keys[@]}"; do
    recipients="$recipients --recipient $key"
  done
  
  # Encrypt with logging
  gpg --encrypt $recipients --output "$output" "$file"
  echo "Encrypted $file to $output for ${#team_keys[@]} recipients"
}

9.4 SIEM Integration

Audit log parsing for SIEM systems (example Logstash filter):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
filter {
  if [program] == "gpg" {
    grok {
      match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{HOSTNAME:hostname} gpg\[%{POSINT:pid}\]: %{GREEDYDATA:gpg_message}" }
    }
    
    if [gpg_message] =~ "encrypted with" {
      mutate {
        add_tag => [ "gpg_encryption_event" ]
      }
    }
    
    if [gpg_message] =~ "There is no assurance this key belongs to the named user" {
      mutate {
        add_tag => [ "gpg_untrusted_key" ]
      }
    }
  }
}

10. Testing and Validation

10.1 Key Verification Tests

1
2
3
4
5
# Verify key integrity
gpg --check-sigs [email protected]

# Test encryption/decryption
echo "Test message" | gpg --encrypt --recipient [email protected] | gpg --decrypt

10.2 Security Audit Script

Create a file named audit-gpg-setup.sh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash
# GPG Security Audit Script

echo "=== GPG VERSION ==="
gpg --version

echo "=== CHECKING GPG CONFIGURATION ==="
grep -E "^(personal-digest-preferences|cert-digest-algo|default-preference-list)" ~/.gnupg/gpg.conf

echo "=== CHECKING DIRECTORY PERMISSIONS ==="
ls -ld ~/.gnupg
ls -la ~/.gnupg | grep -E "\.conf$|\.gpg$"

echo "=== KEY EXPIRATION STATUS ==="
gpg --list-keys --list-options show-unusable-subkeys | grep -E "^pub|^sub" | grep -E "expired|expires"

echo "=== CHECKING FOR REVOCATION CERTIFICATES ==="
find ~/.gnupg -name "*revocation*"

echo "=== ANALYZING KEY STRENGTH ==="
gpg --list-keys --with-colons | grep -E "^pub|^sub" | awk -F: '{print $5}'

echo "=== CHECKING AGENT CONFIGURATION ==="
grep -E "^(default-cache-ttl|max-cache-ttl)" ~/.gnupg/gpg-agent.conf

echo "=== TESTING ENCRYPTION PERFORMANCE ==="
dd if=/dev/urandom of=/tmp/testfile bs=1M count=10 2>/dev/null
time gpg --batch --recipient [email protected] --output /tmp/testfile.gpg --encrypt /tmp/testfile
rm /tmp/testfile /tmp/testfile.gpg

Make the script executable and run it:

1
2
chmod +x audit-gpg-setup.sh
./audit-gpg-setup.sh > gpg-audit-results.txt

10.3 Red Team Considerations

Test scenarios to validate your PGP implementation:

  1. Passphrase cracking: Attempt to crack weak passphrases using tools like John the Ripper
  2. Metadata analysis: Examine what information is leaked in encrypted communications
  3. Key harvesting: Test if keys are inadvertently exposed in repositories or backups
  4. Side-channel attacks: Measure timing differences in encryption operations
  5. Social engineering: Test procedures for key verification and fingerprint checking

11. Troubleshooting

11.1 Common Issues and Solutions

ProblemPossible CauseSolution
“No secret key”Private key not availableImport private key or check GNUPGHOME path
“Bad passphrase”Incorrect passphraseTry alternative passphrases or recover from backup
“Unusable public key”Encryption to expired/revoked keyGet updated public key from recipient
“Inappropriate ioctl for device”Missing TTY for passphrase entryUse export GPG_TTY=$(tty)
“Resource temporarily unavailable”gpg-agent issuesRestart with gpgconf --kill gpg-agent

11.2 Diagnostic Commands

1
2
3
4
5
6
7
8
9
10
11
# Check agent status
gpgconf --list-options gpg-agent

# Show key details
gpg --list-keys --with-subkey-fingerprints

# Verbose debug output
gpg --verbose --debug-level advanced --decrypt file.gpg

# Check what keyserver is configured
gpg --list-options | grep keyserver

11.3 Recovery Procedures

11.3.1 Key Recovery

1
2
3
4
5
6
7
# Import from backup
gpg --import private_key_backup.asc

# If passphrase is forgotten (and no backup exists)
# Unfortunately, there is no direct recovery path
# Without the passphrase, the key is lost
# This is by design for security

11.3.2 Trust Database Rebuilding

1
2
3
4
5
# Back up existing trust database
cp ~/.gnupg/trustdb.gpg ~/.gnupg/trustdb.gpg.bak

# Rebuild trust database
gpg --check-trustdb

12. References and Further Reading

12.1 Official Documentation

12.2 Known CVEs and Vulnerabilities

CVEDescriptionAffected VersionsMitigation
CVE-2018-12020“Efail” - Direct exfiltration via HTMLGnuPG before 2.2.8Update GnuPG, disable HTML email
CVE-2017-7526Side-channel vulnerability in LibgcryptLibgcrypt before 1.7.8Update Libgcrypt
CVE-2014-4617Chosen-ciphertext attack against MDCGnuPG before 1.4.18Update GnuPG

12.3 Books and Papers

12.4 Community Resources

13. Appendices

13.1 Glossary of Terms

TermDefinition
Key pairA set of mathematically related keys: public (shared) and private (secret)
Key IDShort identifier for a key (last 8 or 16 hex digits of fingerprint)
FingerprintFull 40-character hexadecimal identifier of a key
Web of trustDecentralized trust model where users sign each other’s keys
SubkeyAdditional key associated with a primary key, often used for encryption
RevocationProcess of marking a key as no longer valid
KeyserverPublic directory that distributes public keys
KeyringLocal collection of public or private keys

13.2 Sample Configurations for Different Security Levels

13.2.1 Basic Security (Personal Use)

1
2
3
4
# ~/.gnupg/gpg.conf
personal-digest-preferences SHA256
cert-digest-algo SHA256
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed

13.2.2 Enhanced Security (Professional Use)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# ~/.gnupg/gpg.conf
personal-digest-preferences SHA512 SHA384 SHA256
cert-digest-algo SHA512
default-preference-list SHA512 SHA384 SHA256 AES256 AES192 AES ZLIB BZIP2 ZIP Uncompressed
no-emit-version
no-comments
export-options export-minimal
keyid-format 0xlong
with-fingerprint
use-agent
verify-options show-uid-validity
list-options show-uid-validity
keyserver hkps://keys.openpgp.org
keyserver-options no-honor-keyserver-url

13.2.3 Maximum Security (High-Value Keys)

1
2
3
4
5
6
7
8
9
10
# ~/.gnupg/gpg.conf
# All of the enhanced security settings, plus:
default-key 0xYOUR_SUBKEY_ID  # Use subkey, not master key
encrypt-to 0xYOUR_KEY_ID      # Always encrypt to yourself
hidden-encrypt-to 0xYOUR_KEY_ID  # Hidden recipient (doesn't appear in metadata)
throw-keyids                  # Don't include recipient key IDs (more private)
s2k-cipher-algo AES256        # Strong symmetric encryption
s2k-digest-algo SHA512        # Strong hash algorithm for passphrase protection
s2k-mode 3                    # Use iterated and salted passphrase hashing
s2k-count 65011712            # Maximum passphrase iteration (more secure)

13.3 Migration Guide

13.3.1 Moving from PGP to GnuPG

  1. Export keys from commercial PGP:
    1
    2
    
    pgp --export-key "Your Name" > pubkey.pgp
    pgp --export-secret-key "Your Name" > seckey.pgp
    
  2. Import into GnuPG:
    1
    2
    
    gpg --import pubkey.pgp
    gpg --allow-secret-key-import --import seckey.pgp
    
  3. Update trust database:
    1
    2
    3
    4
    5
    
    gpg --edit-key [email protected]
    > trust
    > 5
    > y
    > save
    

13.3.2 Upgrading from GnuPG 1.x to 2.x

  1. Back up your existing keys and configuration:
    1
    
    cp -r ~/.gnupg ~/.gnupg.backup
    
  2. Export keys in a format compatible with both versions:
    1
    2
    
    gpg --export --armor > public_keys.asc
    gpg --export-secret-keys --armor > private_keys.asc
    
  3. Install GnuPG 2.x according to section 4

  4. Import your keys into the new version:
    1
    2
    
    gpg --import public_keys.asc
    gpg --import private_keys.asc
    
  5. Update trust database:
    1
    
    gpg --import-ownertrust ~/.gnupg.backup/trustdb.gpg
    
  6. Verify successful migration:
    1
    2
    
    gpg --list-keys
    gpg --list-secret-keys
    

13.4 Key Server Considerations

13.4.1 Public Key Server Options

Key ServerFeaturesConsiderations
keys.openpgp.orgModern, privacy-respectingEmail verification required for email address association
keyserver.ubuntu.comWell-maintainedNo verification of email addresses
pgp.mit.eduLong-establishedHistorical option, less reliable recently

13.4.2 Running a Private Key Server

For organizations needing internal key management:

1
2
3
4
5
6
7
8
# Install SKS keyserver (example for Debian/Ubuntu)
sudo apt install sks

# Initialize the database
sudo -u sks sks build

# Configure membership with other servers if desired
sudo -u sks sks peer

Configure sksconf file for security hardening:

1
2
3
4
5
pagesize: 16
ptree_pagesize: 16
disable_mailsync: 1
hostname: keyserver.example.com
server_contact: [email protected]

13.5 Script Library

13.5.1 Batch Encryption Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
# batch-encrypt.sh - Encrypt multiple files for multiple recipients

RECIPIENTS=("0xABC123" "0xDEF456")
FILES=("$@")

if [ ${#FILES[@]} -eq 0 ]; then
  echo "Usage: $0 file1 [file2 ...]"
  exit 1
fi

for file in "${FILES[@]}"; do
  if [ ! -f "$file" ]; then
    echo "Error: File '$file' not found."
    continue
  fi
  
  RECIPIENT_ARGS=""
  for recipient in "${RECIPIENTS[@]}"; do
    RECIPIENT_ARGS="$RECIPIENT_ARGS --recipient $recipient"
  done
  
  echo "Encrypting $file..."
  gpg --batch --yes $RECIPIENT_ARGS --encrypt "$file"
  
  if [ $? -eq 0 ]; then
    echo "Success: $file encrypted to $file.gpg"
  else
    echo "Error: Failed to encrypt $file"
  fi
done

13.5.2 Key Expiration Monitoring Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/bash
# key-monitor.sh - Check PGP key expiration dates and send alerts

WARN_DAYS=30
EMAIL="[email protected]"

# Get list of keys that will expire soon
EXPIRING_KEYS=$(gpg --list-keys --with-colons | grep -E "^(pub|sub)" | 
  awk -F: '$5 != "" && $5 != "0" {print $5 " " $10}' | 
  while read exptime keyid; do
    # Convert timestamp to date
    expdate=$(date -d @$exptime +%Y-%m-%d 2>/dev/null)
    today=$(date +%Y-%m-%d)
    days_left=$(( ($(date -d "$expdate" +%s) - $(date -d "$today" +%s)) / 86400 ))
    
    if [ $days_left -lt $WARN_DAYS ] && [ $days_left -gt 0 ]; then
      echo "Key $keyid will expire in $days_left days ($expdate)"
    fi
  done)

# Send alert if there are keys expiring soon
if [ -n "$EXPIRING_KEYS" ]; then
  echo -e "PGP Key Expiration Warning\n\nThe following keys will expire soon:\n\n$EXPIRING_KEYS" | 
    mail -s "PGP Key Expiration Alert" $EMAIL
fi

13.5.3 Automated Key Backup Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/bash
# key-backup.sh - Create encrypted backups of PGP keys

BACKUP_DIR="$HOME/pgp-backups"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
BACKUP_FILE="$BACKUP_DIR/pgp-backup-$TIMESTAMP.tar.gpg"

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"

# Create temporary directory for collecting files
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT

# Export public and private keys
gpg --export --armor > "$TEMP_DIR/public-keys.asc"
gpg --export-secret-keys --armor > "$TEMP_DIR/private-keys.asc"
gpg --export-ownertrust > "$TEMP_DIR/trust.txt"

# Copy configuration files
cp ~/.gnupg/gpg.conf "$TEMP_DIR/gpg.conf" 2>/dev/null
cp ~/.gnupg/gpg-agent.conf "$TEMP_DIR/gpg-agent.conf" 2>/dev/null

# Create tar archive and encrypt it with password
tar -cf - -C "$TEMP_DIR" . | gpg --symmetric --cipher-algo AES256 --output "$BACKUP_FILE"

# Set secure permissions on the backup file
chmod 600 "$BACKUP_FILE"

echo "Backup created: $BACKUP_FILE"
echo "Remember to store this file securely offline."

13.6 Compliance Considerations

13.6.1 GDPR Implications

When using PGP for protecting personal data under GDPR:

  • Document key management procedures as part of technical measures
  • Include key recovery procedures in data protection impact assessments
  • Consider encryption as a factor in breach notification requirements
  • Implement appropriate key rotation and revocation policies

13.6.2 Industry-Specific Requirements

IndustryRegulationPGP Implementation Considerations
HealthcareHIPAADocument key management in security policies, include in BAAs
FinancialPCI DSSUse 4096-bit keys, implement dual control measures
GovernmentFIPS 140-2Ensure implementations use validated cryptographic modules
LegalAttorney-client privilegeDocument chain of custody for encrypted communications

13.6.3 Compliance Checklist

  • Document key management procedures
  • Implement key rotation schedules
  • Maintain logs of encryption/decryption activities
  • Create and test key recovery procedures
  • Train users on secure passphrase management
  • Conduct regular security assessments
  • Update PGP implementation to address known vulnerabilities
  • Include encryption in data protection impact assessments

14. Change Log

VersionDateChanges
1.0.02025-05-09Initial guide creation
1.0.12025-05-10Added hardware key section, expanded troubleshooting
1.1.02025-05-15Added compliance section, updated security recommendations

This guide is maintained by the Security Team. Last updated: May 9, 2025.

This post is licensed under CC BY 4.0 by the author.