Using GPG Keys to Secure Data Confidentiality and Integrity

Estimated read time: 15 min

An Introduction to GPG

Cryptography is a word that may strike fear into the hearts of non-technical folks. It's intimidating because it sounds complicated and learning about it can feel overwhelming. This guide aims to simplify the introduction of cryptography into your everyday life. For that, we're going to focus on the use of GPG keysβ€”specifically, the RSA 3072 asymmetric key pair. Is that a mouthful? Let's keep it simple by calling them a GPG key pair. Each GPG key pair is split into public and private keys that are used for the following operations:

  • Encrypting and decrypting data.
  • Digitally signing files to verify their authenticity and integrity.
  • Verifying signed files to ensure they haven't been tampered.

Public and Private Key Examples

Several types of asymmetric key pairs exist, but the RSA 3072 is what you'll see most often. They follow a common format that begins with a key header, followed by a Base64 encoded key, and ending with a footer that's nearly identical to the header. The header and footer distinctly identify the beginning and end of a key block.

A GPG public key in ASCII-armored format looks like:

-----BEGIN PGP PUBLIC KEY BLOCK-----
mQENBFxhz7cBCADJc0IkrftQv+bG1DqN53+5KyiRk+mc+V5FZkDglgn9GQh2HvOz...
-----END PGP PUBLIC KEY BLOCK-----

A GPG private key in ASCII-armored format looks like this:

-----BEGIN PGP PRIVATE KEY BLOCK-----
lQOYBFxhz7cBCADJc0IkrftQv+bG1DqN53+5KyiRk+mc+V5FZkDglgn9GQh2HvOz...
-----END PGP PRIVATE KEY BLOCK-----

Generating Your Key Pair

Open your command line and type the following:

# command:
gpg --gen-key

# output:
gpg: key 3C4FA637544D94D4 marked as ultimately trusted
gpg: revocation certificate stored as '/home/user/.gnupg/openpgp-revocs.d/3C4FA637544D94D4.rev'
public and secret key created and signed.

pub rsa4096 2024-12-13 [SC] [expires: 2026-12-13]
3C4F A637 544D 94D4 9864 C5AC 294C 5727 54AF D654
uid [ultimate] John Doe (Test Key) <[email protected]>
sub rsa4096 2024-12-13 [E] [expires: 2026-12-13]

Don't worry about doing anything with your key pair yet. It's safely nestled in its home on your machine. Let's first learn what we can do with it.


Using The Public Key

How Can Public Keys Be Used?

A public key is used in the following ways:

  • Encrypting data that only the corresponding private key can decrypt.

    • this is achieved by instructing your machine to encrypt a message using the recipient's public key

    • a sender will use your public key to encrypt messages they're sending to you

  • Verifying the authenticity of data signed with the corresponding private key.

    • this is achieved by instructing your machine to verify a digital signature using the corresponding public key

    • while this sounds complicated, you'll find it quite trivial once the mental concept sticks

Β 

How Do Public Keys Work?

  • One or more users generates a key-pair

  • Each user distributes their public key via email, messenger, a website, or key servers

  • Every user who intends to encrypt data or verify signatures obtains the following:

    • To encrypt data:

      • the receiver's (to whom you're sending data) public key
    • To verify signatures:

      • a signature file and public key
        • OR (more on this later)
      • a source file, signature file, and public key
  • Users who are encrypting data use the receiver's public key to encrypt the data before transmission.

  • Users who are verifying a signature use the signer's public key to reverse the signature and compare the source to the reversed signature. This process uses hashing to quickly and securely compare the two files. Don't worry, this step is easier than it sounds.

Β 

Exporting Your Public Key

Sharing your public key requires that your first export it. Open your command line and run the following command:

# command:
gpg --export --armor -o public-key.asc

# output file: public-key.asc
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQENBFxhz7cBCADJc0IkrftQv+bG1DqN53+5KyiRk+mc+V5FZkDglgn9GQh2HvOz...
-----END PGP PUBLIC KEY BLOCK-----

This command saves the public key as public-key.asc in a human-readable ASCII format. You may share this output file with anyone who needs to verify your signature or encrypt data they want to send to you.

πŸ’‘ Tip
It is safe and common to share your public key.

Β 

Importing a Public Key

Using a public key requires that you first load it into your keychain. There are a number of ways to accomplish this, but we'll focus on importing a public key from a file. Other methods are listed below, but wait to review them until the intitial concepts are cemented in your mind.

Importing a public key from a file
# command:
gpg --import public-key.asc # load the public key file

# output:
gpg: key 294C572754AFD654: public key "John Doe <[email protected]>" imported
gpg: Total number processed: 1
gpg: imported: 1
Importing a public key from a keyserver
# command to download and import:
gpg --keyserver hkps://keyserver.ubuntu.com --recv-keys 3C4FA637544D94D49864C5AC294C572754AFD654 # fetch by key ID

# output:
gpg: key 294C572754AFD654: public key "John Doe <[email protected]>" imported
gpg: Total number processed: 1
gpg: imported: 1
Importing a public key from a url
# download the file:
curl -O https://example.com/public-key.asc

# command to import:
gpg --import public-key.asc

# output:
gpg: key 294C572754AFD654: public key "John Doe <[email protected]>" imported
gpg: Total number processed: 1
gpg: imported: 1
Verify the imported key's fingerprint

When you first import a key you'll want to verify the key's fingerprint to confirm the integrity and authenticity of the key. The long line of digits in the following command is the key's ID. It's obtained in the output from when you first loaded the public key.

# command to fingerprint:
gpg --fingerprint 3C4FA637544D94D49864C5AC294C572754AFD654

# output:
pub rsa4096 2024-12-01 [SC] [expires: 2026-12-01]
3C4F A637 544D 94D4 9864 C5AC 294C 5727 54AF D654
uid [ultimate] John Doe <[email protected]>
sub rsa4096 2024-12-01 [E] [expires: 2026-12-01]

Compare the fingerprint from the output to the fingerprint you obtained from the sender. The key can be trusted if they're an exact match.

Β 

Common Digital Signature Formats

Digital signatures generally exist in one of four formats. Two of these (clearsigned and embedded) combine the digital signature artifacts into a single file. Clearsigned signature files always contain a plaintext message. Think of it as a digitally signed memo with a signature verifying that the message is authentic to the claimed author. Clearsigned and embedded signatures are typically used for documents and communication while detached signatures are typically used for signing software executables.

Signature TypeValidation RequirementsExtensionHuman Readable
Clearsignedsignature file + public key.ascyes
Embeddedsignature file + public key.gpgno
Detached (ASCII)source file + signature file + public key.ascyes
Detached (binary)source file + signature file + public key.signo

⚠️ Warning
Digitally signed files do not offer any form of privacy or confidentiality. They exist only to ensure authenticity and integrity of files. Privacy and confidentiality requires encryption.

Β 

A Note On Complex Commands

The command line is inherently complex. It's a powerful tool that can be intimidating at first, but you'll eventually start to feel like Neo from The Matrix. Until then, it helps to understand a few key concepts:

ConceptDescription
Command:The instruction you're giving your machine.
Flag:A modifier that changes the behavior of a command. Flags are preceded by a hyphen (-) or double hyphen (--) and are followed by a value.
Output:The result of a command. This can be a file, a message, or a change in the system.
Error:A message that indicates something went wrong. Errors can be benign or critical.
Taget:The file or directory that a command is acting on.

Let's break down one of the more complex commands so you can truly understand what's happening:

gpg --encrypt --armor --recipient [email protected] -o encrypted-msg.asc msg.txt

CommandDescription
gpginvokes gpg
--encryptinstructs gpg to encrypt
--armoroutput file in human-readable format
--recipientnext input is recipient email
[email protected]recipient email
-osave output to file
encrypted-msg.ascspecified output filename
msg.txtname of file you're encrypting

If you really want to get nitty-gritty, you can read the GPG manual.

Β 

Verifying Digital Signatures

Verifying digitals signature is simple once you understand the concepts. This section reviews how to verify all four signature types.

Verifying a clearsigned document
# command to verify:
gpg --verify message.txt.asc

# output:
gpg: Signature made Fri Dec 13 16:25:32 2024 PST
gpg: using RSA key 3C4FA637544D94D49864C5AC294C572754AFD654
gpg: issuer "[email protected]"
gpg: Good signature from "John Doe <[email protected]>" [ultimate]
Verifying an embedded signature
# command to verify:
gpg --verify signed-file.txt.gpg

# output:
gpg: Signature made Fri Dec 13 16:27:43 2024 PST
gpg: using RSA key 4310AC20ADE7PD2A7657B0CE69E50CDA1E0C3GOQ
gpg: Good signature from "Jane Doe <[email protected]>" [ultimate]
Verifying a detached ASCII signature
# command to verify:
gpg --verify file.txt.asc file.txt

# output:
gpg: Signature made Fri Dec 13 16:29:21 2024 PST
gpg: using RSA key 3310AB20ADE7CD2A7057B0CE69E55CDA1E0C3AED
gpg: Good signature from "Jimi Hendrix <[email protected]>" [ultimate]
Verifying a detached binary signature
# command to verify:
gpg --verify file.sig file.txt

# output:
gpg: Signature made Fri Dec 13 16:31:14 2024 PST
gpg: using RSA key 7320AB20ADE7CF2A7697V9CE69E55CDA1E0C3AHW
gpg: Good signature from "Marylin Monroe <[email protected]>" [ultimate]

Β 

Encrypting Data

Encrypting data is relatively simple. You'll need the recipients public key and a file to encrypt. You can encrypt in human readable and binary formats:

Encrypting in human readable format:
# create a file with some content:
echo "This is a test message." > message.txt

# command to encrypt:
gpg --encrypt --armor --recipient [email protected] message.txt

# output file: encrypted-message.asc
-----BEGIN PGP MESSAGE-----
hQEMA5yBF+H0Z1+1AQgAqOjK+nbNRkwX+d4S+b0eJQpM1xRmVRCH...
-----END PGP MESSAGE-----
Encrypting in binary
# create a file with some content:
echo "This is a test message." > message.txt

# command to encrypt:
gpg --encrypt --recipient [email protected] message.txt

# output file: encrypted-message.gpg
the output in this file is not human readable

These operations append .asc or .gpg to the end of the file name. You'll share message.txt.asc|gpg with the recipient.


Using Your Private Key

How Can Your Private Key Be Used?

A private key can be used in the following ways:

  • Decrypting information encrypted with the corresponding public key.

    • this is achieved by instructing your machine to decrypt files using your own private key
  • Signing files to prove that the data originated from you and hasn't been tampered with.

    • this is achieved by instructing your machine to sign files using your own private key

Β 

How Do Private Keys Work?

The concept of a private key is generally more simple than a public key. Private keys are stored locally and used for only two operations:

  • A user recieves encrypted and instructs their machine to decrypt that data using their private key

  • A user generates a file they want to sign and instructs their machine to sign that file using their private key

Β 

Exporting Your Private Key

It is possible to export your private key to a file in a few scenarios where it's helpful:

  1. Backing it up on an encrypted USB drive or a secure offline storage device.
  2. Transferring your key to a new device such as a new laptop or workstation.
  3. When migrating from one GPG tool to another.
  4. Revoking your key and issuing a new one.
  5. Automating secure operations: this is an advanced use case that most non-technical users can ignore.

Command to Export Your Private Key

# command to export:
gpg --export-secret-keys --armor -o private-key.asc

# output file: private-key.asc
-----BEGIN PGP PRIVATE KEY BLOCK-----
lQOYBFxhz7cBCADJc0IkrftQv+bG1DqN53+5KyiRk+mc+V5FZkDglgn9GQh2HvOz...
-----END PGP PRIVATE KEY BLOCK-----

The key is stored as private-key.asc

⚠️ Warning

It is not safe to share your private key with anyone for any reason. Anyone who gains access to your private key can impersonate you, sign files in your name, or decrypt sensitive data intended for you.

Specifying a Key When You Own Multiple

If you have multiple keys, export a specific key by providing the key ID or email:

# command to export selected:
gpg --export-secret-keys <key-ID-or-email> --armor -o private-key.gpg

# output file: private-key.gpg
-----BEGIN PGP PRIVATE KEY BLOCK-----
lQOYBFxhz7cBCADJc0IkrftQv+bG1DqN53+5KyiRk+mc+V5FZkDglgn9GQh2HvOz...
-----END PGP PRIVATE KEY BLOCK-----

Β 

Managing Your Private Key

Never Share Your Private Key!

  • The private key must be kept secret and secure at all times.

Tips for Managing Your Private Key

  1. Use a Strong Passphrase:
    • Protect your private key with a strong, unique passphrase. Learn the difference betwen a strong and weak passphrase with this password strength meter.
  2. Backup Securely:
    • Store backups in a secure, offline location (e.g., encrypted USB drive or hardware security module).
  3. Revoke If Compromised:
    • If your private key is lost or compromised, revoke it immediately using a revocation certificate.

Β 

Signing Documents

Now, onto the good stuff. This section reviews how to use your private key to sign documents. Remember that there are four common types of signatures.

Clearsigning a document
# creating a file to clearsign:
echo "This is a test message." > message.txt

# command to clearsign:
gpg --clearsign message.txt

# output file: message.txt.asc
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
This is a clearsigned message!
-----BEGIN PGP SIGNATURE-----
iQHDBAEBCAAtFiEEPE+mN1RNlNSYZMWsKUxXJ1Sv1lQFAmdc0HwPHGZha2VAZW1h...
-----END PGP SIGNATURE-----
Sign with embedded signature
# command
gpg --sign message.txt

# output file: message.txt.gpg
the output in this file is not human readable
Sign with detached signature (ASCII)
# command
gpg --armor --detach-sign message.txt

# output file: message.txt.asc
-----BEGIN PGP SIGNATURE-----
iQGzBAABCAAdFiEEkf4nRdL0P5TEf1fRXg3GD+n5kQ8FAmdhhSQACgkQXg3GD+n5...
-----END PGP SIGNATURE-----
Sign with detached signature (binary)
# command:
gpg --detach-sign message.txt

# output file: message.txt.sig
the output in this file is not human readable

Β 

Decrypting Data

Decrypting data that was encrypted using your public key is relatively straightforward. You have two main options in this scenarioβ€”print to command line or output to file.

Print to command line
# command to decrypt:
gpg --decrypt encrypted-file.gpg

# output (prints to command line):
gpg: encrypted with 3072-bit RSA key, ID 7A46Q1914223B653, created 2023-12-11
This message was encrypted using your public key. Congrats on making it to the end of this guide!
Output To file
# command to decrypt:
gpg -o decrypted-file.txt --decrypt encrypted-file.gpg

# output file: decrypted-file.txt
gpg: encrypted with 3072-bit RSA key, ID 7A46Q1914223B653, created 2023-12-11
This message was encrypted using your public key. Congrats on making it to the end of this guide!

Practice Practice Practice

Behind every great artist is a body of failed work. Your mound of mistakes becomes the foundation of your success. To simplify the practice of these concepts you can create a directory structure on your machine specifically for GPG key management. Use that folder as your starting point.

gpg_practice/
β”œβ”€β”€ gpg_keys/
β”‚ β”œβ”€β”€ public-key.gpg # represents your personal public key
β”‚ β”œβ”€β”€ mary-public-key.gpg # represents a friend's public key
β”‚ β”œβ”€β”€ bob-public-key.gpg # represents a colleague's public key
β”‚ β”œβ”€β”€ private-key.gpg # represents your private key
β”œβ”€β”€ sig_files/
β”‚ β”œβ”€β”€ clearsigned.txt.asc # clearsigned file to practice verifications
β”‚ β”œβ”€β”€ clearsigned_tampered.txt.asc # clearsigned file that you modify to practice verification failures
β”‚ β”œβ”€β”€ embedded.txt.gpg # file with an embedded signature
β”‚ β”œβ”€β”€ detachedASCII.txt.asc # detached ASCII signature
β”‚ β”œβ”€β”€ detachedbinary.txt.sig # detached binary signature
β”œβ”€β”€ data_files/
β”‚ β”œβ”€β”€ test_file.txt # test file that is subject to signatures, encryption, and decryption
β”‚ β”œβ”€β”€ test_file_two.txt # test file that is subject to signatures, encryption, and decryption
β”œβ”€β”€ encrypted_files/
β”‚ β”œβ”€β”€ armored_encrypted.txt.asc # file encrypted in ASCII format (armored)
β”‚ β”œβ”€β”€ encrypted.txt.gpg # file encrypted in binary format
└── notes.txt # file to keep notes on your practice

The advent of AI is moving privacy and authenticity to the center stage. Learning the fundamentals of online privacy and security is a critical skill for the future. GPG keys are a great place to start. They're simple to use and provide a solid foundation for understanding more complex cryptographic concepts.