🔐 GPG Encryption & Decryption: Setup, Usage & Troubleshooting


GPG (GNU Privacy Guard) is a powerful tool for secure file encryption, decryption, and key management. This guide walks you through key creation, file encryption, decryption, and troubleshooting issues — especially common in minimal environments like Alpine Linux, WSL, and Docker.


🔐 GPG Key Setup

Generate a New Key Pair

gpg --full-generate-key

Choose:

  • RSA and RSA
  • 2048 or 4096 bits
  • Expiration (or none)
  • Name/email
  • Passphrase (you'll need this to decrypt)

View Your Keys

Secret (Private) Keys:

gpg --list-secret-keys

Public Keys:

gpg --list-keys

🛡️ Encrypt a File (Asymmetric)

echo "This is secret data" > secret.txt

gpg --encrypt --recipient your@email.com secret.txt

This creates secret.txt.gpg.

Decrypt the File

gpg --decrypt secret.txt.gpg

You’ll be prompted for your key passphrase via pinentry.


🔐 Encrypt with a Passphrase (Symmetric)

For testing or simple sharing:

gpg --symmetric test.txt

Then decrypt:

gpg --decrypt test.txt.gpg

🛠️ Troubleshooting GPG Issues

❌ No Secret Key / Can't Decrypt

Error:

gpg: public key decryption failed: No secret key
gpg: decryption failed: No secret key

Fix:

List and verify:

gpg --list-secret-keys

Ensure your private key is imported:

gpg --import private-key.asc

❌ No pinentry / GPG Hangs or Stalls

Error:

gpg: public key decryption failed: No pinentry

Fix (Alpine Linux):

apk add pinentry pinentry-tty
echo "pinentry-program /usr/bin/pinentry-tty" >> ~/.gnupg/gpg-agent.conf
export GPG_TTY=$(tty)
gpgconf --kill gpg-agent
gpgconf --launch gpg-agent

Verify:

gpg-connect-agent /bye

❌ GPG Agent Broken or Socket Missing

Fix:

gpgconf --kill all
rm -rf ~/.gnupg/S.gpg-agent*
gpgconf --launch gpg-agent
export GPG_TTY=$(tty)

Add this to .bashrc or .zshrc:

export GPG_TTY=$(tty)

🔍 Debugging Decryption

Use verbose mode:

gpg -vv --decrypt file.gpg

Check file type:

file file.gpg

Check agent status:

pgrep -a gpg-agent

🔄 Export & Import Keys

Export Public Key

gpg --export -a 'User Name' > public.asc

Export Private Key

gpg --export-secret-keys -a 'User Name' > private.asc

Import Keys

gpg --import public.asc
gpg --import private.asc

🔒 Clean Up & Reset GPG Agent

gpgconf --kill all
rm -rf ~/.gnupg/S.gpg-agent*
gpgconf --launch gpg-agent

✅ Recap: Quick Test Flow

gpg --full-generate-key
echo "secret" > test.txt
gpg --encrypt --recipient your@email.com test.txt
gpg --decrypt test.txt.gpg

For symmetric testing:

gpg --symmetric test.txt
gpg --decrypt test.txt.gpg

📌 Tips

  • Always export and back up your private key securely.
  • For automation, avoid GUI pinentry — use pinentry-tty in headless environments.
  • Use gpg-agent for managing passphrase prompts across sessions.

Got stuck? Run gpg -vv --decrypt file.gpg and check the key ID and agent logs.
This guide should cover 90% of real-world GPG setup and debugging issues.