A Gentle Introduction to GPG for Encrypted Message Exchange

Have you ever noticed that some people, especially those in cryptography or tech-savvy circles, include their GPG key in their contact information? For a long time, I thought this was one of the coolest things a person could do—it’s like saying, “Hey, I’m serious about security, and I know my stuff”. Recently, I found myself working on a project that made me appreciate GPG even more. It involved sending and receiving files to banks over SFTP, which required encrypting and decrypting files with GPG. This experience gave me a hands-on understanding of how GPG works and why it’s such a powerful tool. In this post, I want to share that experience with you. I’ll explain what GPG is, how it’s different from PGP, and most importantly, how you can use it yourself. Whether you want to secure your files, protect your communication, or simply feel like a cryptography pro, GPG is a tool worth knowing—and sharing your key might just be the coolest thing you can do.

Gold Mask on the Ground From Pexels

Background

GPG (GNU Privacy Guard) combines the power of symmetric and asymmetric encryption to securely exchange data. Here’s a simplified explanation of how it works:


🙋‍♂️ You may consider to enroll my top-rated cryptography course on Udemy

Public Key Cryptography From Scratch

PGP Scheme

Step 1: Generate a Random Symmetric Key

When you encrypt a message or file, GPG first generates a random symmetric key. This key is used to encrypt the actual content using a fast and secure symmetric encryption algorithm, like AES.

Step 2: Encrypt the Symmetric Key with the Public Key

Next, GPG encrypts the symmetric key itself using the recipient’s public key. This step ensures that only the recipient, who possesses the corresponding private key, can decrypt and retrieve the symmetric key.

Step 3: Send the Encrypted Message and Key

The encrypted content and the encrypted symmetric key are bundled together and sent to the recipient.

Step 4: Receiver Decrypts the Symmetric Key

The recipient uses their private key to decrypt the encrypted symmetric key. Since the private key is unique to the recipient, no one else can access the symmetric key.





Step 5: Use the Symmetric Key for Decryption

Once the symmetric key is decrypted, the recipient can use it to decrypt the actual content and retrieve the original message or file.

Why GPG Is Secure and Efficient

– Each time you encrypt data with GPG, it generates a new symmetric key. This randomness ensures that even if you encrypt the same message multiple times, the ciphertext will always be different.
– Symmetric encryption algorithms like AES are much faster than asymmetric ones, making this hybrid approach both secure and efficient.
– The use of public/private keys ensures that only the intended recipient can decrypt the symmetric key, securing the entire process.

This combination of symmetric and asymmetric encryption strikes a balance between performance and security, making GPG an ideal tool for secure communication and file sharing.

Generating Your GPG Keys

Before you can start encrypting or decrypting files, you need to generate your own GPG keys. This involves creating a pair of keys: one public and one private. The public key is what you share with others, while the private key stays with you and is used to decrypt messages or files encrypted with your public key.

First, make sure GPG is installed on your system. You can install it using the following commands:

sudo apt update
sudo apt install gnupg

Run the following command to start the key generation process:

gpg --full-generate-key

This command will guide you through the setup process. Here’s what you’ll need to provide:

Key type: Choose the default option, which is usually “RSA and RSA”.
Key size: Use a key size. 3072-bit RSA key is equivalent to 128-bit AES key which is thought safe beyond 2030.
Expiration date: Set this to 0 for no expiration.
User ID: Enter your name and email address. This is used to identify the key while you listing keys.
Passphrase: Set a strong passphrase to protect your private key.





Once your key is generated, you can list it with the following command:

# list public keys
gpg --list-keys

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

Exporting your keys

Export your key public-private key pair using the following command:

# export my public key
gpg –armor –export serengil@gmail.com > serengil-pub.asc

# export my private key
gpg –armor –export-secret-keys serengil@gmail.com > serengil-priv.asc

The –armor option ensures the key is saved in a text-based format, making it easier to store securely. Also, exporting private key will ask your passphrase.

Your private key is critical for decrypting messages and files encrypted with your public key. It’s important to keep this key safe and never share it with anyone. Losing your private key means you’ll lose access to encrypted files, and sharing it compromises your security.

Importing Someone Else’s Public Key

To send encrypted files or messages to someone else, you need their public key. Once you have their public key, you can import it into your GPG keyring and use it to encrypt files or messages for them.

I cloned Dr. Tanja Lange‘s public key for this experiment. You can clone my public key in your experiment.

gpg --import tanja-2020.asc

You should see output confirming the key was imported successfully:

gpg: key 82865C3243CECE97: public key "Tanja Lange <tanja@hyperelliptic.org>" imported
gpg: Total number processed: 1
gpg:               imported: 1

After importing the key, it’s a good practice to verify it:





gpg --list-keys

This will display my public key and Lange’s public key I just imported.

/home/sefik/.gnupg/pubring.kbx
------------------------------
pub   rsa3072 2024-12-19 [SC]
      ECA0B32A46F96AA70CEEFD7C30F6E6D21EE91C2F
uid           [ultimate] Sefik Serengil <serengil@gmail.com>
sub   rsa3072 2024-12-19 [E]

pub   rsa4096 2020-02-09 [SC]
      A0DD00F5AEFA6086FEEF178E82865C3243CECE97
uid           [ unknown] Tanja Lange <tanja@hyperelliptic.org>
sub   rsa4096 2020-02-09 [E]

When you need to send an encrypted file or message to this person, you’ll use their public key. For example, to encrypt a file message.txt for Dr. Lange:

gpg --armor --output message.gpg --encrypt --recipient tanja@hyperelliptic.org message.txt

This command creates an encrypted file named message.gpg that only she can decrypt using their private key.

-----BEGIN PGP MESSAGE-----

hQIMAz3PgQH4JT+0ARAA4JDus9EGtiOv3bGL/vjS74IiAk84jIVKKpSSHzsNBazc
qZ7O2R0/k6vPF1c8jzIEU9lAnDKyYDPR6e7GE0lADV+JuDaX4DJ4v3NhRIGPvU1H
EaPL+2QYvBjzBq9pjFEVcjhXX+0HJT4juCFQHPascO0Xfvxtlck3mZ60mgghAC7r
NO2vjqc/AskWHhpOKlQg/SUDySMXaYWcZBnKeK7/08PymLUENOkKS7jXj8mLjl6b
DDq6LfhG5uaNwAp9SILv3JwxaLT/VAMlv7IvARk1P+G+SWx0gjFpxihgBff9DDN/
Dsg1YE91/MvQL+g1vMlYVs1K8biaK4h35l1KYOMMxmC4d8Q6AdqXNlnFOCGJ6T9Y
JobtSOPOVrA3UjFKzBs6pNXaV7caAtY6KZWo3tJRNFI78pkP9FQ5v5xpAev99vJK
rSnjlEMvdLueaDWQNPsRcmfqnJwicF8iHzyUedKFROBxI8u3XOrSq6GYhCO9FrTj
ORZUs/D29jWaWAfs/zWw8B3+N1Ve0j6XVCuT2S5tm1rVRX+9bfYKENOgMsWfFty+
e3QRkbO3ATxzYJlY4IA4y7WvtG0N69KN4hhWdY0MHlZ9pg6tRaM9qkwDblSB7dbv
SCaJ2ZD4jIIn0yzV/kH1DC8y0EMDggS746kNsGjOWoIG0gEtYXHTRz9yEaJ1owvS
vQFIi2OvHwk1wlZ6RnuYzIebOXUCazPtSGx5H9aMyLUShw0sZQNvRzMoSpLR5y/E
UD/nBP056Ekltv7gWxEO8cX4SVq+sIuqqZqK39BLQ4DzuPJBmWvG4zh9WPbvj46l
qIQRCMaS6uMZlBZqSPFGSJhZbkGg2q3cOlIosJkO2by/oMRd7effb1oaoqCpsh6E
qtOB2KsXUNO7AETRTvE9eHBMd/3KhNTzPg1Hnd/IOBXiw5UZJ1kHwJDyf/CedQ==
=xFwo
-----END PGP MESSAGE-----

With this setup, you can securely communicate with others, knowing that only they can read the files or messages you send.

Decrypting an Encrypted Message

If someone has sent you an encrypted message using your public key, you can decrypt it using your private key. Here’s how to do it step by step. Use the following command to decrypt the file:

gpg --output decrypted-message.txt --decrypt message.gpg

If your private key is protected by a passphrase, GPG will prompt you to enter it just after you run decrypt command. Provide your passphrase to proceed.

Python

You can use Python to work with GPG for encryption and decryption. The gnupg library simplifies this process. Here’s how to encrypt and decrypt messages using Python.

Install the required library using pip:

pip install python-gnupg

The GPG instance will automatically load the keys that were imported via the terminal. If you have already imported keys using the terminal, they will be available for use here. Otherwise, they will be imported by python program.

import gnupg

# Initialize the GPG instance
gpg = gnupg.GPG()

name, mail, key_file = ("Tanja Lange", "tanja@hyperelliptic.org", "tanja-2020.asc")
imported_users = [imported_key["uids"][0] for imported_key in gpg.list_keys()]

if f"{name} <{email}>" not in imported_users:
   with open(key_file, 'r') as key_file:
      gpg.import_keys(key_file.read())

Here’s an example of encrypting a message using someone’s public key:





message = "This is a secret message for Someone."

encrypted_data = gpg.encrypt(
    message,
    recipients=['tanja@hyperelliptic.org'],
    always_trust=True  # Trust the recipient's key without manual confirmation
)

assert encrypted_data.ok is True

# Save the encrypted message to a file
with open('message.gpg', 'w') as encrypted_file:
    encrypted_file.write(str(encrypted_data))

To decrypt a message that was encrypted with your public key:

with open('message.gpg', 'r') as encrypted_file:
    encrypted_message = encrypted_file.read()

decrypted_data = gpg.decrypt(
    encrypted_message, passphrase=MY_PASSPHRASE
)

assert decrypted_data.ok is True

print(decrypted_data.data.decode())

Conclusion

In this post, we’ve explored why sharing your GPG key with your email address is not just a cool practice but also a powerful way to ensure secure communication. By combining both symmetric and asymmetric encryption, GPG provides a robust method to keep your messages private and protected.

While GPG might seem complex at first, it’s a valuable tool for anyone who prioritizes privacy and security in their digital interactions. Whether you’re exchanging sensitive information, collaborating with others, or just getting started with encryption, understanding GPG and how it works can make a big difference in maintaining your privacy online.

So, next time you share your email, consider attaching your GPG key to it – not only does it boost your security, but it also adds an extra layer of trust to your communications. After all, in a world where privacy is increasingly hard to come by, it’s cool to be secure!


Support this blog if you do like!

Buy me a coffee      Buy me a coffee


Leave a Reply