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. Introduction

In this tutorial, we’ll examine how to deal with java.security.UnrecoverableKeyException. We’ll also explore the details of what this exception actually means and what causes it. Finally, we’ll review possible solutions to this problem.

2. Theory Background

In Java, we have a notion of a keystore. It is essentially a file that contains some secrets. What it can contain, in particular, is certificate chains along with private keys for them. Since the certificate is just a fancy public-key wrapper, we can essentially state that the keystore contains an asymmetric key pair.

Usually, it is a good practice to protect our private keys with a password (‘password’ also commonly referred to as ‘passphrase’). It is a good practice not only in Java keystores but also in cybersecurity in general. The way this protection is usually implemented is by encrypting the private key with the password using a symmetric key encryption algorithm, such as various flavors of AES instances.

What is important for us here is that private keys in the keystore can be encrypted with the password, just like we described. This feature is available not in all keystore types, for instance JKS keystores support private key password protection, but PKCS12 keystores does not. In our example, we’ll need a password protection feature, so we’re going to work with JKS keystores from now on.

3. UnrecoverableKeyException Origins

A java.security.UnrecoverableKeyException typically occurs when we’re working with KeyManagerFactory, specifically when we invoke init() method on it. This is the class from JSSE that allows us to retrieve KeyManager instances. KeyManager is basically the interface that represents the abstraction responsible to authenticate us as clients to our peers.

The init() method takes two arguments – the source keystore to get credentials for authentication from and the password for private key decryption. The java.security.UnrecoverableKeyException occurs when KeyManagerFactory cannot recover the certificate chain’s private key. Here comes the question – what does ‘recover’ actually mean? Well, it means that the private key for the certificate chain cannot be decrypted with the given password. So, therefore, the most common by far source of java.security.UnrecoverableKeyException is the wrong password for the private key in the keystore.

To sum up, if the password/passphrase we provided for KeyManagerFactory for private keys is incorrect, then KeyManagerFactory won’t be able to decrypt the keys, and therefore, we have this error.

4. Simulating the Exception

Let’s get our hands dirty and try to simulate this error. For this, we’ll need a JKS keystore with a private key and corresponding certificate pair. We can achieve this by using the keytool:

$ keytool -genkey -alias single-entry -storetype JKS -keyalg RSA -validity 365 -keystore single_entry_keystore.jks

Once we run this command, keytool will prompt us for a couple of additional information. In our case, it would be some additional info to generate a certificate (CN, expiration, etc.) and the password for both the keystore and the private key. Let’s assume that we’ve chosen an ‘admin123’ password for the keystore and a ‘privateKeyPassword’ passphrase for the private key.

In order to load this keystore in Java, we would do this:

public static X509ExtendedKeyManager initializeKeyManager() 
  throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException, URISyntaxException {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore instance = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream resourceAsStream = Files.newInputStream(Paths.get(ClassLoader.getSystemResource("single_entry_keystore.jks").toURI()));
    instance.load(resourceAsStream, "admin123".toCharArray());
    kmf.init(instance, "privateKeyPassword".toCharArray());
    return (X509ExtendedKeyManager) kmf.getKeyManagers()[0];
}

We obtained the instance of KeyManager from the Keysotre we’ve just created. This code works fine since both passwords are correct. If we changed the password for the private key in the example above, we would get a java.security.UnrecoverableKeyException. So, just using the correct password would solve this problem.

5. UnrecoverableKeyException Edge Cases

There are some corner cases, that can cause the java.security.UnrecoverableKeyException that most people are unaware of. Let’s discuss them one by one.

5.1. Multiple Private Key Entries

For instance, let’s imagine a scenario where we do not have a single private key/certificate chain in the keystore but multiple of them. Let’s create a new keystore with two keys in it:

$ keytool -genkey -alias entry-1 -storetype JKS -keyalg RSA -validity 365 -keystore multi_entry_keystore.jks
$ keytool -genkey -alias entry-2 -storetype JKS -keyalg RSA -validity 365 -keystore multi_entry_keystore.jks

So here, we’ve added two private keys with certificate entries to the keystore. Let’s assume that we’ve added the first private key with password ‘abc123’, and the second one with the password ‘bcd456’. That should be perfectly fine, after all, keystore can have multiple keys encrypted with different passwords, no problem here so far.

Now, the code for building KeyManager for the given keystore would not change – it would look exactly like we already did above. The only problem here is that the KeyManagerFactory.init() method only accepts one password for the private key decryption.

That seems strange – what password exactly are we supposed to provide here – ‘abc123’, or ‘bcd456’? Well, it turned out that Sun JSSE implementation of KeyManagerFactory, which is used in an overwhelming amount of JDKs, is, by default, expecting a single password for each private key in the keystore. That’s right, even though having two private keys in the keystore encrypted with different passwords is technically not a problem. There is no restriction on this from a theoretical standpoint; however, there is one from the API standpoint.

We cannot have different passwords for any two given keys in the keystore. If we violate this rule, the KeyManagerFactory implementation would try to decrypt all keys with the provided password, and of course, it would fail for at least one key. Therefore, KeyManagerFactory.init() would throw an exception because it could not decrypt the key – and that’s right, it was not able indeed. So we absolutely need to keep this in mind.

5.2. External Libraries Restrictions

As Software Engineers, we don’t often interact with JSSE directly. Frameworks usually hide this by creating multiple layers of abstraction for us. However, we should understand that we still interact with KeyManager and other JSSE classes indirectly by using various clients, such as Apache HTTP client or Apache Tomcat.

And these frameworks can and often do impose various constraints on what passwords they expect. For instance, the current Apache Tomcat implementation relies on the fact that the keystore password is equal to the password of the private keys in the keystore. These restrictions can differ from one library to another, but now, as we understand the cause of java.security.UnrecoverableKeyException, we should know where to dig. So, be aware of the frameworks used in the project and their implementation limitations.

6. Conclusion

In this article, we’ve explored everything we need to know about java.security.UnrecoverableKeyException – what causes it, and ways to fix it. We’ve understood that java.security.UnrecoverableKeyException is thrown by KeyManagerFactory to signal the inability to decrypt the private keys inside the keystore. That, as mentioned, happens primarily due to an incorrect decryption key (the password).

There are some nuances to know about as well. For instance, we cannot have multiple private keys within the keystore with different passwords. This is not acceptable from a JSSE standpoint. We should also beware of the constraints of different frameworks for dealing with keystores and private keys.

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)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments