1. Overview

Security is paramount in software applications where encryption and decryption of sensitive and personal data are basic requirements. All of these cryptographic APIs are included with the JDK as part of JCA/JCE, and others come from third-party libraries such as BouncyCastle.

In this tutorial, we’ll learn about the basics of PGP and how to generate the PGP key pair. Furthermore, we’ll learn about PGP encryption and decryption in Java using the BouncyCastle API.

2. PGP Cryptography Using BouncyCastle

PGP (Pretty Good Privacy) encryption is a way to keep data secret, and there are only a few OpenPGP Java implementations available, like BouncyCastle, IPWorks, OpenPGP, and OpenKeychain API. These days, when we talk about PGP, we nearly invariably refer to OpenPGP.

PGP uses two keys:

  • A public key of the recipient is used for the encryption of messages.
  • A private key of the recipient is used for the decryption of messages.

In a nutshell, there are two participants: the sender (A) and the recipient (B).

If A wishes to send an encrypted message to B, then A encrypts the message with BouncyCastle PGP using B’s public key and sends it to him. Later, B uses its private key to decrypt and read the message.

BouncyCastle is a Java library that implements PGP encryption.

3. Project Setup and Dependencies

Prior to beginning the encryption and decryption process, let’s set up our Java project with the necessary dependencies and create the PGP key pair that we’ll need later.

3.1. Maven Dependency for BouncyCastle

Firstly, let’s create a simple Java Maven project and add the BouncyCastle dependencies.

We’ll add bcprov-jdk15on, which contains a JCE provider and lightweight API for the BouncyCastle Cryptography APIs for JDK 1.5 and up. Also, we’ll add bcpg-jdk15on, which is a BouncyCastle Java API for handling the OpenPGP protocol and contains the OpenPGP API for JDK 1.5 and up:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.68</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpg-jdk15on</artifactId>
    <version>1.68</version>
</dependency>

3.2. Install GPG Tool

We’ll use the GnuPG (GPG) tool to generate a PGP key pair in ASCII (.asc) format.

Let’s first install GPG on our system if we haven’t already:

$ sudo apt install gnupg

3.3. Generate PGP Key-Pair

Before we jump to encryption and decryption, let’s first create a PGP key pair.

First, we’ll run the command to generate the key pair:

$ gpg --full-generate-key

Next, we need to follow the prompts to choose the key type, key size, and expiration date.

For example, let’s choose RSA as the key type, 2048 as the key size, and the expiration date for 2 years.

Next, we’ll enter our name and email address:

Real name: baeldung
Email address: [email protected]
Comment: test keys
You selected this USER-ID:
    "baeldung (test keys) <[email protected]>"

We need to set a passphrase to secure the key and make sure it’s strong and unique. Using a passphrase isn’t strictly mandatory for PGP encryption, but it’s highly recommended for security reasons. When generating a PGP key pair, we can choose to set a passphrase to protect our private key, adding an extra layer of security.

If an attacker gets hold of our private key, setting a strong passphrase ensures the attacker cannot use it without knowing the passphrase.

Let’s create the passphrase once prompted by the GPG tool. For our example, we have chosen baeldung as the passphrase.

3.4. Export the Keys in ASCII Format

Finally, once the key is generated, we export it in the ASCII format using the command:

$ gpg --armor --export <our_email_address> > public_key.asc

This creates a file named public_key.asc containing our public key in ASCII format.

In the same way, we’ll export the private key:

$ gpg --armor --export-secret-key <our_email_address> > private_key.asc

Now we’ve got a PGP key pair in ASCII format, consisting of a public key public_key.asc and a private key private_key.asc.

4. PGP Encryption

For our example, we’ll have a file that contains our message in plain text. We’ll encrypt this file with a public PGP key and create a file with the encrypted message.

We’ve taken references from the BouncyCastle example for PGP implementation.

First, let’s create a simple Java class and add an encrypt() method:

public static void encryptFile(String outputFileName, String inputFileName, String pubKeyFileName, boolean armor, boolean withIntegrityCheck) 
  throws IOException, NoSuchProviderException, PGPException {
    // ...
}

Here, outputFileName is the name of the output file, which will have the message in an encrypted format.

Also, inputFileName is the name of the input file that contains the message in plain text, and publicKeyFileName is the name of the public key file name.

Here, if armor is set to true, we’ll use ArmoredOutputStream, which uses an encoding similar to Base64, so that binary non-printable bytes are converted to something text-friendly.

Furthermore, withIntegrityCheck specifies whether the generated encrypted data will be secured by an integrity packet or not.

Next, we’ll open the streams for the output file:

OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFileName));
if (armor) {
    out = new ArmoredOutputStream(out);
}

Now, let’s read the public key:

InputStream publicKeyInputStream = new BufferedInputStream(new FileInputStream(pubKeyFileName));

Next, we’ll use the PGPPublicKeyRingCollection class for managing and utilising public key rings in PGP applications, allowing us to load, search, and use public keys for encryption.

A public key ring in PGP is a group of public keys, each linked to a user ID (such as an email address). Many public keys can be included on a public key ring, enabling a user to have many identities or key pairs.

We’ll open a key ring file and load the first available key suitable for encryption:

PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKeyInputStream), new JcaKeyFingerprintCalculator());
PGPPublicKey pgpPublicKey = null;
Iterator keyRingIter = pgpPub.getKeyRings();
while (keyRingIter.hasNext()) {
    PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();
    Iterator keyIter = keyRing.getPublicKeys();
    while (keyIter.hasNext()) {
        PGPPublicKey key = (PGPPublicKey) keyIter.next();
        if (key.isEncryptionKey()) {
            pgpPublicKey = key;
            break;
        }
    }
}

Next, let’s compress the file and get a byte array:

ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(inputFileName));
comData.close();
byte[] bytes = bOut.toByteArray();

Furthermore, we’ll create a BouncyCastle PGPEncryptDataGenerator class for streaming out and writing data to it:

PGPDataEncryptorBuilder encryptorBuilder = new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setProvider("BC")
  .setSecureRandom(new SecureRandom())
  .setWithIntegrityPacket(withIntegrityCheck);
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(encryptorBuilder);
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));
OutputStream cOut = encGen.open(out, bytes.length);
cOut.write(bytes);

Finally, let’s run the program to see if our output file is created with our file name and if the content looks like this:

-----BEGIN PGP MESSAGE-----
Version: BCPG v1.68

hQEMA7Bgy/ctx2O2AQf8CXpfY0wfDc515kSWhdekXEhPGD50kwCrwGEZkf5MZY7K
2DXwUzlB5ORLxZ8KkWZe4O+PNN+cnNy/p6UYFpxRuHez5D+EXnXrI6dIUp1XmSPY
22l0v5ANwn7yveS/3PruRTcR0yv5tD0pQ+rZqH9itC47o9US+/WHTWHyuBLWeVMC
jTCd7nu3p2xtoKqLOMIh0pqQtexMwvLUxRJNjyQl4CTsO+WLkKkktQ+QhA5lirx2
rbp0aR7vIT6qhPjahKln0VX2kbIAJh8JC4rIZXhTGo+U/GDk5ph76u0F3UvhovHN
X++D1Ev6nNtjfKAsYUvRANT+6tHfWmXknsZ2DpH1sNJUAbEAYTBPcKhO3SFdovuN
6fbhoSnChNTBln63h67S9ZXNSt+Ip03wyy+OxV9H1HNGxSHCa+dtvkgZT6KMuEOq
4vBqPdL8vpRT+E60ZKxoOkDyxnKJ
=CYPG
-----END PGP MESSAGE-----

5. PGP Decryption

As part of decryption, we’ll decrypt the file created in the previous step using the recipient’s private key.

First, we’ll create a decrypt() method:

public static void decryptFile(String encryptedInputFileName, String privateKeyFileName, char[] passphrase, String defaultFileName) 
  throws IOException, NoSuchProviderException {
    // ...
}

Here, the argument inputFileName is the file name that needs to be decrypted.

Next, privateKeyFileName is the file name for the private key, and passphrase is the secret passphrase selected during the key pair generation.

Also*, defaultFileName* is the default name for the decrypted file.

Let’s open an input stream on the input file and private key file:

InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
InputStream keyIn = new BufferedInputStream(new FileInputStream(privateKeyFileName));
in = PGPUtil.getDecoderStream(in);

Then, let’s create a decryption stream, and we’ll use BouncyCastle’s PGPObjectFactory for the OutputStream:

JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
// The first object might be a PGP marker packet.
if (o instanceof PGPEncryptedDataList) {
    enc = (PGPEncryptedDataList) o;
} else {
    enc = (PGPEncryptedDataList) pgpF.nextObject();
}

Furthermore, we’ll use PGPSecretKeyRingCollection to load, find, and utilize secret keys for decryption. Next, we’ll load secret keys from a file:

Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = 
  new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator());
while (sKey == null && it.hasNext()) {
    pbe = (PGPPublicKeyEncryptedData) it.next();
    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(pbe.getKeyID());
    if(pgpSecKey == null) {
        sKey = null;
    } else {
        sKey = pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC")
          .build(passphrase));
    }
}

Now, once we get the private key, we’ll use this private key from the collection to decrypt encrypted data or messages:

InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC")
  .build(sKey));
JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
Object message = plainFact.nextObject();
if (message instanceof PGPCompressedData) {
    PGPCompressedData cData = (PGPCompressedData) message;
    JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
    message = pgpFact.nextObject();
}
if (message instanceof PGPLiteralData) {
    PGPLiteralData ld = (PGPLiteralData) message;
    String outFileName = ld.getFileName();
    outFileName = defaultFileName;
    InputStream unc = ld.getInputStream();
    OutputStream fOut = new FileOutputStream(outFileName);
    Streams.pipeAll(unc, fOut);
    fOut.close();
}
privateKeyInStream.close();
instream.close();

Lastly, we’ll use the methods isIntegrityProtected() and verify() of PGPPublicKeyEncryptedData to verify the integrity of the packet:

if (pbe.isIntegrityProtected() && pbe.verify()) {
    // success msg
} else {
    // Error msg for failed integrity check
}

After that, let’s run the program to see if the output file is created with our file name and if the content is in plaintext:

//In our example, decrypted file name is defaultFileName and the msg is:
This is my message.

6. Conclusion

In this article, we learned how to do PGP encryption and decryption in Java using the BouncyCastle library.

Firstly, we learned about PGP key pairs. Secondly, and most importantly, we learned about the encryption and decryption of a file using the BouncyCastle PGP implementation.

As always, the full example code for this article is available over on GitHub.