eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)