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.

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

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]
Encrypt With Someone’s Public Key
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:
# create a plain message echo "Dear Dr. Lange, I have been following your research for a long time, and you influenced me a lot. Wanted to share my respect. Regards." > message.txt # encrypt message 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+0AQ/+Mx/WlxGC0C0F/oTdp/fndAmuXWt/Wzog3Cf42tG8ryc9 KuUE37QcXJQ/7d1AXDbOvq6hmYL+QRgVet4BahfqfBibk4ZIwT9uj2eJgdrsi9Dd nOsM4AXIwLAZc7uGO+yYYrEHSEEdRIz4RlXz7UpTIYAxylESXBi5ElL76dm6FsSM qvD1lodZNFkcOdZ5J+PZLurpD7Fh+9MloKI51SlaDp40d1cREp3MPffXdk5ZWzYS avtaBD2qVj7syVuqSSzF23qP7a+sZhdtXlg1YY81Ft0f3PD4VbWZwHOSmrGKqCTA Mg/HI6/5Lq24+ovAdPYhxpjy32CgWUBLyNaq0GYh7jA+Vn7u7bXbMz3f1Mc4CMcy k9h3tLBB/4NvwHMFCD6Xn4GpGBetkLTc8vLpR8PbpHEfrJ/kHl0TuBDxR3Pw+2VL 16c+2ziEKDZxz+93ypvoA93V+sY4Crox7aFv5up7a4TioSHYff+6IgtuQufX4F1L HAEuT8XouCstf79XsrY+m/mx8Vf65hFist2jIzlSp9TkInJf3fvK0WpBZ9WFhuHb /9gf4lFP7zV0QApb4aQsMzkIL1HxsizOp+bObdZTCHn8PsIPUaercUMu/pzkZaef cnW1GrVyLztxc7wdbT9RuG9RnEAE+WtKBjeHO79x6lWzT61pIHFwbKFZ6hD1fKfS sAGE8iUhOo7ZoFvojA11GzcM2HQqtSjQouLh2uBvAATvRcQGRlnUWY6smBU6DY07 46IPh+B4ccVBAEkaxXi9Kk+rBYJjNmpx2bqvLva60iV6wuktCo5tMOP5EXzKWLlz XmIL3Pc5LAi2lhuMXY9fFpv35DLvI10CwZxOwpnHqgZ953vp9V/xWsbLWANjppOQ c54xgMiI7SMHPr86/znV8DzlYSUOp0Ot8HgJ1QbsOeP6 =K5xQ -----END PGP MESSAGE-----
With this setup, you can securely communicate with others, knowing that only they can read the files or messages you send.
Adding Signature
In previous section, I encrypted a message with Dr. Lange’s public key. But how can she confirm that the message is coming from me? She can only be sure if and only if I added my signature. I encrypt the plain with her public key. Meanwhile, I should sign the message with my private key. Then, she can verify it with my public key. Notice that my public key is already publicly available.
gpg --armor --output message.gpg --encrypt --sign --local-user serengil@gmail.com --recipient tanja@hyperelliptic.org message.txt
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'], sign="serengil@gmail.com", 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 assert decrypted_data.signature is True: print(f"decrypted message is {decrypted_data.data.decode()}") print(f"Signed by: {decrypted_data.username}")
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!