Introduction
PGP, which stands for Pretty Good Privacy, was written by Phil Zimmermann in 1991 as a tool for activists and journalists to communicate securely. The first version was released as freeware on Usenet and quickly spread around the world despite a criminal investigation by US Customs into whether Zimmermann had violated munitions export laws by publishing strong cryptography. In this pgp encryption java tutorial we will build a PGP-style hybrid encryption pipeline using the standard java.security and javax.crypto APIs.
PGP is not a single algorithm. It is a hybrid protocol that combines symmetric encryption, asymmetric encryption, digital signatures, and compression. The reason is simple: symmetric ciphers like AES are fast and can encrypt gigabytes, but they require a pre-shared key; asymmetric ciphers like RSA can wrap a key without prior contact, but they are slow and limited to small messages. PGP uses RSA to encrypt a freshly generated AES key, then uses AES to encrypt the actual message. Optionally, it signs the message first with the sender's RSA private key.
What is PGP Style Encryption?
PGP-style encryption refers to a hybrid scheme where the sender generates a fresh symmetric session key, encrypts the message with that session key using AES, and then encrypts the session key with the recipient's RSA public key. The output is the concatenation of the encrypted session key and the encrypted message. The recipient decrypts the session key with their RSA private key, then decrypts the message with AES.
The full OpenPGP format, defined in RFC 4880, adds additional layers: compression before encryption, digital signatures for authentication, and a packet structure that allows multiple recipients and key IDs. Real implementations such as GnuPG and Bouncy Castle's OpenPGP API implement this full format. For this tutorial we build a simplified version that captures the essential security properties without the OpenPGP packet complexity.
Compared to raw AES, PGP-style hybrid encryption lets you encrypt a large message to a recipient whose only public information is their RSA public key. Compared to raw RSA encryption, hybrid encryption is much faster and has no message-size limit. Compared to TLS, PGP is asynchronous: the sender can encrypt without the recipient being online, and the recipient can decrypt without contacting anyone.
How PGP Style Encryption Works Step by Step
Suppose Alice wants to send a 1-kilobyte message to Bob using PGP-style encryption.
Step 1: Alice generates a random 256-bit AES key with a CSPRNG.
Step 2: Alice encrypts the message with AES-GCM using the session key. She produces the ciphertext and an authentication tag.
Step 3: Alice encrypts the session key with Bob's RSA public key using RSA-OAEP padding. The output is a 256-byte encrypted key blob.
Step 4: Alice (optionally) signs the ciphertext with her own RSA private key, producing a signature.
Step 5: Alice transmits the encrypted session key, the ciphertext, the authentication tag, and (optionally) the signature to Bob.
Step 6: Bob decrypts the session key with his RSA private key. He then decrypts the message with AES-GCM using the recovered session key. The authentication tag ensures the ciphertext was not tampered with in transit.
Step 7: If a signature is present, Bob verifies it with Alice's public key.
Java Program for PGP Style Encryption Using Bouncy Castle
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Base64;
public class PgpStyleDemo {
static class PgpEnvelope {
byte[] encryptedSessionKey;
byte[] ciphertext;
byte[] iv;
PgpEnvelope(byte[] k, byte[] c, byte[] iv) {
this.encryptedSessionKey = k;
this.ciphertext = c;
this.iv = iv;
}
}
public static PgpEnvelope encrypt(String message, PublicKey recipientPub) throws Exception {
// 1. Generate a random AES-256 session key
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey sessionKey = kg.generateKey();
// 2. Encrypt the message with AES-GCM
byte[] iv = new byte[12];
new SecureRandom().nextBytes(iv);
Cipher symCipher = Cipher.getInstance("AES/GCM/NoPadding");
symCipher.init(Cipher.ENCRYPT_MODE, sessionKey, new GCMParameterSpec(128, iv));
byte[] ciphertext = symCipher.doFinal(message.getBytes("UTF-8"));
// 3. Wrap the session key with RSA-OAEP
Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
rsa.init(Cipher.ENCRYPT_MODE, recipientPub);
byte[] encryptedSessionKey = rsa.doFinal(sessionKey.getEncoded());
return new PgpEnvelope(encryptedSessionKey, ciphertext, iv);
}
public static String decrypt(PgpEnvelope env, PrivateKey recipientPriv) throws Exception {
// 4. Unwrap the session key
Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
rsa.init(Cipher.DECRYPT_MODE, recipientPriv);
byte[] sessionKeyBytes = rsa.doFinal(env.encryptedSessionKey);
SecretKey sessionKey = new javax.crypto.spec.SecretKeySpec(sessionKeyBytes, "AES");
// 5. Decrypt the message
Cipher symCipher = Cipher.getInstance("AES/GCM/NoPadding");
symCipher.init(Cipher.DECRYPT_MODE, sessionKey, new GCMParameterSpec(128, env.iv));
byte[] plain = symCipher.doFinal(env.ciphertext);
return new String(plain, "UTF-8");
}
public static void main(String[] args) throws Exception {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair pair = gen.generateKeyPair();
String message = "Meet me at the docks at midnight. Bring the documents.";
System.out.println("Plaintext : " + message);
PgpEnvelope env = encrypt(message, pair.getPublic());
System.out.println("Encrypted session key (b64): "
+ Base64.getEncoder().encodeToString(env.encryptedSessionKey));
System.out.println("Ciphertext (b64): "
+ Base64.getEncoder().encodeToString(env.ciphertext));
String recovered = decrypt(env, pair.getPrivate());
System.out.println("Decrypted : " + recovered);
}
}
Code Explanation Line by Line
The PgpEnvelope class is a tiny container for the three pieces of data the recipient needs: the encrypted session key, the ciphertext, and the IV. In a real OpenPGP message this would be encoded as a sequence of packets; we use a plain Java class for simplicity.
The encrypt method does the symmetric encryption first. We generate a 256-bit AES session key, generate a 12-byte IV for GCM (GCM uses 96-bit IVs by convention), and run AES-GCM over the message bytes. GCM is an authenticated encryption mode: it produces both a ciphertext and a 16-byte authentication tag, which the decryptor will check before accepting the plaintext.
We then wrap the session key with RSA-OAEP, the recommended RSA encryption padding scheme. OAEP uses a hash function and a random seed to make RSA encryption probabilistic and resistant to chosen-ciphertext attacks. The transformation string "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING" specifies OAEP with SHA-256 as the hash function and MGF1 as the mask generation function.
The decrypt method mirrors encrypt. We first unwrap the session key with the RSA private key, reconstruct the SecretKey object, and then run AES-GCM in decrypt mode. The GCM tag verification happens automatically; if the tag does not match, doFinal throws an AEADBadTagException.
The main method generates a 2048-bit RSA key pair, encrypts a message, prints the encrypted blob, and decrypts it back to the original string. The output exactly matches the input, which proves the round trip works.
Sample Input and Output
Plaintext : Meet me at the docks at midnight. Bring the documents. Encrypted session key (b64): xJ7kL2p... (long base64) Ciphertext (b64): Vz3jRk... (long base64) Decrypted : Meet me at the docks at midnight. Bring the documents.
The exact encrypted values will differ every run because the AES session key and IV are freshly random, and because RSA-OAEP is itself probabilistic. The crucial fact is that the decrypted text exactly matches the input.
Common Mistakes to Avoid
First, never use raw RSA without OAEP. The transformation "RSA/ECB/PKCS1Padding" is vulnerable to chosen-ciphertext attacks such as Bleichenbacher's attack. Always use OAEP.
Second, never use an unauthenticated mode such as CBC for the symmetric part of a hybrid scheme. CBC provides confidentiality but not integrity, so an attacker can flip bits in the ciphertext and have predictable changes appear in the decrypted plaintext. Use AES-GCM or AES-EAX.
Third, never reuse an IV with the same AES-GCM key. Reusing an IV with GCM is catastrophic: the attacker can recover the authentication key and forge messages. Generate a fresh 12-byte IV with SecureRandom for every message.
Fourth, never sign and encrypt in the wrong order. The standard advice is to sign the plaintext first, then encrypt the signed plaintext. This is the "sign-then-encrypt" pattern; the inverse "encrypt-then-sign" can leak information to an attacker who re-signs a ciphertext.
Real-World Applications
PGP is used by journalists and activists around the world for end-to-end encrypted email. The related OpenPGP standard is implemented by GnuPG, which is the de facto tool for signing and encrypting files on Linux. Software distribution systems use OpenPGP signatures to authenticate packages. Encrypted backup tools often use a PGP-like hybrid scheme to wrap per-file AES keys with an RSA master key.
For modern messaging applications, the Signal protocol has largely replaced PGP because it offers forward secrecy, which PGP lacks by default. But PGP remains the standard for asynchronous communication where forward secrecy is impossible.
If you need full OpenPGP packet compatibility, use Bouncy Castle's org.bouncycastle.openpgp package. The simplified program above shows the cryptographic heart of PGP without the packet complexity.
Conclusion
The full OpenPGP specification, defined in RFC 4880 (and the newer RFC 9580), adds a packet structure on top of the cryptographic core we built here. Each OpenPGP message is a sequence of packets: a one-pass signature packet, a compressed-data packet, a literal-data packet, a public-key encrypted session key packet, a symmetrically encrypted integrity-protected data packet, and so on. The packets are length-prefixed and can be nested. The standard also defines ASCII-armored output, which wraps the binary packets in base64 with human-readable headers for transport over email.
If you need to interoperate with GnuPG or other OpenPGP implementations, you should use Bouncy Castle's org.bouncycastle.openpgp package, which provides a full reader and writer for the OpenPGP packet format. The simplified code in this tutorial is fine for educational purposes and for systems where you control both ends, but it cannot produce messages that GnuPG can decrypt.
In this pgp encryption java tutorial we built a PGP-style hybrid encryption pipeline using only Java's standard javax.crypto and java.security APIs. We combined AES-GCM for the message with RSA-OAEP for the session key, and we saw why authenticated encryption and OAEP padding are essential. The full OpenPGP format adds packet encoding, compression, and signatures, but the cryptographic core is exactly what we have built here.
Comments
Comments
Post a Comment