gpg Command: Tutorial & Examples

Encrypt, decrypt, sign, and verify files and messages using GnuPG

The gpg command is an essential tool for Linux servers that provides cryptographic privacy and authentication based on the OpenPGP standard. It enables encryption and decryption of data, digital signing and verification of files or messages, and comprehensive management of public and private cryptographic keys. This article details how gpg operates, why it is vital for securing communications, and provides practical command-line examples. It also covers common parameters, advanced usage, troubleshooting, security considerations, and related tools.

What gpg Does

The GNU Privacy Guard (gpg) implements the OpenPGP standard to provide several cryptographic functions:

  1. Data Encryption and Decryption
    Encrypt files or messages so that only the intended recipient, holding the correct private key, can decrypt and access the content.

  2. Digital Signatures
    Create signatures that verify the authenticity and integrity of files or messages, proving they originate from a trusted sender.

  3. Key Management
    Generate, import, export, list, and delete cryptographic key pairs (public and private keys).

  4. Key Signing and Trust Management
    Sign other users’ public keys to establish a web of trust and manage trust levels within your keyring.

These features are crucial for protecting sensitive information on Linux servers from unauthorized access, tampering, or impersonation.

How gpg Works

gpg primarily uses asymmetric (public-key) cryptography, involving two mathematically linked keys:

  • Public Key: Shared openly to encrypt data or verify signatures.
  • Private Key: Kept secret by the owner, used to decrypt data or create digital signatures.

When encrypting a message, you use the recipient's public key; only their private key can decrypt it. Conversely, signing is done with your private key, and anyone with your public key can verify the signature.

gpg also supports symmetric encryption, where the same passphrase encrypts and decrypts data, useful for simpler or temporary encryption without key pairs.

Key trust is managed through a "web of trust": users sign others' keys to build confidence in their authenticity. This helps prevent encrypting to malicious keys or accepting forged signatures.

The keyring, typically stored in the ~/.gnupg/ directory, holds your key pairs and trust database. System-wide configurations reside in the /etc/gnupg/ directory.

Why gpg Is Important

On Linux servers, safeguarding data both in transit and at rest is critical. gpg empowers administrators and users to:

  • Secure Emails and Files by encrypting sensitive content before transmission or storage.
  • Verify Data Integrity through digital signatures, ensuring files are unaltered.
  • Authenticate Origins of data by confirming sender identities.
  • Meet Compliance Requirements for data protection and encryption standards.
  • Automate Secure Workflows by integrating gpg in scripts for backups, deployment, or communications.

Without gpg, sensitive server data could be vulnerable to interception, tampering, or impersonation attacks.

Basic Usage

Before encrypting or signing, you need a key pair. Generate one interactively with:

gpg --full-generate-key

Follow the prompts to select key type (usually RSA and RSA), key size (e.g., 2048 or 4096 bits), expiration date, and provide your user ID (name, email).

Encrypt a File for a Recipient

gpg --encrypt --recipient alice@example.com report.pdf

This creates an encrypted file named report.pdf.gpg.

Decrypt an Encrypted File

gpg --decrypt report.pdf.gpg > report.pdf

Sign a File (Cleartext or Binary)

gpg --armor --sign document.txt

Generates document.txt.asc with an ASCII-armored signed message.

Verify a Signature

gpg --verify document.txt.asc

Import a Public Key

gpg --import bob_pubkey.asc

Export Your Public Key (ASCII-Armored)

gpg --armor --export alice@example.com > alice_pubkey.asc

Create a Detached Signature

gpg --detach-sign file.txt

Generates file.txt.sig which can be distributed separately from the file.

Verify a Detached Signature

gpg --verify file.txt.sig file.txt

Encrypt a File Symmetrically

gpg --symmetric secret.txt

Prompts for a passphrase and creates secret.txt.gpg.

Common Command Line Parameters

  • --encrypt : Encrypt data to one or more recipients.
  • --decrypt : Decrypt data.
  • --sign : Create a digital signature.
  • --verify : Verify signatures.
  • --armor : Create ASCII-armored output (text format).
  • --output <file> : Write output to specified file.
  • --recipient <user> : Specify recipient’s public key.
  • --import : Import keys into keyring.
  • --export : Export keys from keyring.
  • --list-keys : List public keys.
  • --list-secret-keys : List private keys.
  • --delete-keys : Delete public keys.
  • --delete-secret-keys : Delete private keys.
  • --full-generate-key : Interactive key generation.
  • --detach-sign : Create detached signature.
  • --symmetric : Use symmetric encryption.
  • --batch : Enable batch mode for scripting.
  • --trust-model <model> : Set trust model (e.g., always, pgp, classic).

Advanced Usage

Using Batch Mode for Automation

gpg --batch --yes --decrypt encrypted_file.gpg

Useful in scripts to avoid interactive prompts.

Fetching Keys from Keyservers

gpg --recv-keys 0x1234ABCD

Downloads a public key from a keyserver.

gpg --send-keys 0x1234ABCD

Uploads your public key to a keyserver.

Using gpg-agent for Passphrase Caching

gpg-agent runs as a daemon managing private keys and caching passphrases, improving security and convenience. It is usually started automatically.

Practical Examples Using gpg

Encrypting a File for Multiple Recipients

gpg --encrypt --recipient alice@example.com --recipient bob@example.com file.txt

Output:

gpg: encrypted with 4096-bit RSA key, ID 1234ABCD, created 2023-06-01
gpg: encrypted with 4096-bit RSA key, ID 5678EFGH, created 2023-05-15
gpg: file 'file.txt.gpg' created

Decrypting a File

gpg --decrypt file.txt.gpg > file.txt

Output:

gpg: encrypted with 4096-bit RSA key, ID 1234ABCD, created 2023-06-01
gpg: decryption successful

Signing a File with Detached Signature

gpg --detach-sign report.pdf

Creates report.pdf.sig.

Verifying a Detached Signature

gpg --verify report.pdf.sig report.pdf

Output if valid:

gpg: Signature made Fri 02 Jun 2023 11:00:00 AM UTC
gpg: Good signature from "Alice Example <alice@example.com>"

Symmetric Encryption

gpg --symmetric notes.txt

Prompts for a passphrase and creates notes.txt.gpg.

Potential Problems and Pitfalls

  • Losing Private Keys or Passphrases
    Without your private key and passphrase, encrypted data cannot be recovered.

  • Trust Issues and Key Verification
    Encrypting to unverified keys risks sending data to malicious parties.

  • File Corruption
    Tampered encrypted files fail to decrypt.

  • Version Compatibility
    Older or incompatible GPG versions may cause errors.

  • Keyserver Availability
    Keyservers may be unreliable or blocked by firewalls.

Troubleshooting and Common Errors

  • "No secret key" error: You tried to decrypt or sign but your private key is missing or not loaded.
  • "Bad signature" error: Signature verification failed due to data corruption or wrong public key.
  • "No public key" error: Cannot encrypt because recipient’s public key is not in your keyring.
  • Permission Denied: Check file permissions on ~/.gnupg/ and keys; they must be readable only by your user.
  • GPG Agent Issues: Restart gpg-agent if passphrase caching behaves unexpectedly.

Tips and Best Practices

  • Verify public keys out-of-band (e.g., in person or via trusted channels) before use.
  • Use strong, memorable passphrases for private keys.
  • Regularly back up your ~/.gnupg/ directory and private keys securely.
  • Use key expiration dates to limit risk from compromised keys.
  • Employ the --armor option to create ASCII output for easier sharing.
  • Automate routine encryption or signing tasks in scripts using batch mode.
  • Regularly update GPG to the latest stable version.
  • Revoke compromised or lost keys promptly.
  • Protect private keys with appropriate filesystem permissions.
  • Use gpg-agent to manage passphrases securely.

Security Considerations

  • Never share your private key or store it unencrypted.
  • Avoid weak or deprecated algorithms (e.g., DSA 1024-bit).
  • Use sufficiently large key sizes (2048-bit RSA minimum, preferably 4096-bit).
  • Be cautious importing keys from untrusted sources.
  • Regularly audit your keyring for unknown or outdated keys.
  • Use hardware tokens or smartcards for private key storage if possible.

Possible Alternatives or Related Commands

  • openssl – General cryptographic toolkit, not OpenPGP compatible.
  • age – Simple modern file encryption tool.
  • ssh-keygen – Generates SSH keys; limited to SSH use cases.
  • gpg-agent – Manages private keys and passphrases for gpg.
  • gpgsm – For S/MIME encryption and signing (different from OpenPGP).
  • gpgconf – Configuration tool for GnuPG components.

Cheatsheet

  • Generate key pair:

    gpg --full-generate-key
    
  • Encrypt file:

    gpg --encrypt --recipient user@example.com file.txt
    
  • Decrypt file:

    gpg --decrypt file.txt.gpg > file.txt
    
  • Sign file (inline):

    gpg --armor --sign file.txt
    
  • Create detached signature:

    gpg --detach-sign file.txt
    
  • Verify signature:

    gpg --verify file.txt.sig file.txt
    
  • Import key:

    gpg --import keyfile.asc
    
  • Export public key:

    gpg --armor --export user@example.com > pubkey.asc
    
  • Symmetric encryption:

    gpg --symmetric file.txt
    

See Also

Further Reading

As an Amazon Associate, I earn from qualifying purchases.

The text above is licensed under CC BY-SA 4.0 CC BY SA