PGP / GPG

The "Pretty Good Privacy" asymmetric encryption scheme used in email and sending encrypted or signed messages

GNU Privacy Guard (GPG)

In Linux, a common command-line utility to perform PGP actions is the gpg program. See a small reference here:

A short list of useful GPG commands to encrypt, decrypt, sign or manage keys

Signing and Verifying

Putting a signature under a message can prove that a certain private key owner has written the message. Anyone can verify it with your public key, but only you can create it with your private key. This is often found in the following format:

It is very recognizable and easy to understand. The first part is the readable plaintext message, and the second part is the signature of that text above, signed (encrypted) with the sender's private key. If anyone wants to verify the validity, they would need to take your public key, and decrypt the signature to be left with an exact match of the text above.

In practice, you can sign a message like this:

If you don't have a keypair yet, you can generate one with:

or import an existing one with:

To then verify it, make sure to first have the public key from the sender imported:

Afterward, you can verify any messages they send came from that key:

Encrypting and Decrypting

If a message is intended for only a specific person to be able to read it, you can encrypt it with their public key so only they can decrypt it with their private key. An encrypted PGP message looks like this:

It is generated by encrypting the message with the recipient's public key, which means you first need to have imported their key like shown before. Then use the following options:

  • -e: to select encryption

  • -r [name or ID]: to select the recipient public key

  • -a: Add "armor" to the resulting file, meaning it is simply an ASCII format in Base64 and BEGIN/END instead of the regular .gpg binary format

For example:

When the recipient wants to read this message, they have to decrypt it with their private key. Simply using the -d option will automatically find the correct key used and owned by you:

You can also encrypt and sign at the same time, using both options ( -s and -e) together

Python

Using the PGPy module you can easily automate any PGP tasks like generating keys, signing/verifying messages and encrypting/decrypting messages.

Official documentation of PGPy with examples for common tasks

This can also be useful to generate low-level keys where you can easily control exactly what data is in the name, comment or email. If an application parses these fields in some what it may be worth trying to inject unexpected data in here like any other field on a website.

Here is a simple example of generating a key and signing a message:

Last updated