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

The Cipher object is an important Java class that helps provide us with encryption and decryption functionality.

In this article, we’re going to take a look at some common exceptions that can occur while we’re using it to encrypt and decrypt text.

2. NoSuchAlgorithmException: Cannot Find Any Provider Supporting X

If we run the following code to get an instance of a Cipher using a made-up algorithm:

Cipher.getInstance("ABC");

We’ll see a stack trace beginning:

java.security.NoSuchAlgorithmException: Cannot find any provider supporting ABC
    at javax.crypto.Cipher.getInstance(Cipher.java:543)

What’s actually going on here?

Well, to use Cipher.getInstance, we’ll need to pass in an algorithm transformation as a String, and this has to be a permitted value listed in the documentation. If it isn’t, we’ll get a NoSuchAlgorithmException.

If we’ve checked the documentation and we’re still seeing this, we’d better make sure that we check the transformation for errors.

We can also specify an algorithm mode and padding in our transformation.

Let’s make sure the values of these fields match the given documentation too. Otherwise, we’ll see an exception:

Cipher.getInstance("AES/ABC"); // invalid, causes exception

Cipher.getInstance("AES/CBC/ABC"); // invalid, causes exception

Cipher.getInstance("AES/CBC/PKCS5Padding"); // valid, no exception

Remember that if we do not specify these extra fields, then the default values will be used.

The default value for algorithm mode is ECB, and the default value for padding is “NoPadding”.

As ECB is considered to be weak, we’re going to want to specify a mode to ensure we don’t end up using it.

To summarize, when resolving a NoSuchAlgorithmException, we’re going to want to review that each part of our chosen transformation exists in the permitted list in the documentation, taking care to check for any typos in our spelling.

3. IllegalBlockSizeException: Input Length Not Multiple of X Bytes

There are a couple of reasons why we might see this exception.

First, let’s look at the exception that’s thrown when we’re trying to decrypt, and then let’s look at it while we’re trying to encrypt.

3.1. IllegalBlockSizeException During Decryption

Let’s write a very simple decryption method:

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
		
return cipher.doFinal(cipherTextBytes);

The behavior of this code will change depending on the cipher text passed into our method, which we probably don’t control.

Sometimes, we may see an IllegalBlockSizeException:

javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
    at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1109)
    at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1053)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
    at javax.crypto.Cipher.doFinal(Cipher.java:2168)

So what does ‘block size’ actually mean, and what makes it ‘illegal’?

To understand this, let’s remember that AES is an example of a Block Cipher.

A block cipher works by taking fixed-length groups of bits called blocks.

To find out how many bytes are in a block for our algorithm, we can use:

Cipher.getInstance("AES/ECB/PKCS5Padding").getBlockSize();

From this, we can see that AES uses blocks of 16 bytes.

This means that it will take a block of 16 bytes, perform the relevant algorithmic steps, and then move on to the next block of 16 bytes.

Simply put, an illegal block is one that does not contain the correct number of bytes.

Normally, this occurs on the final block when the text length isn’t a multiple of 16 bytes.

This typically means that the text to decrypt wasn’t encrypted properly, to begin with, and thus, can’t be decrypted.

Remember that we don’t control the input that’s given to our code to decrypt, so we must be ready to handle this exception.

Therefore, methods like cipher.doFinal throw an IllegalBlockSizeException to force us to handle this scenario, either by throwing it or in a try-catch statement. Otherwise, the code won’t compile.

However, remember that roughly once in every 16 times, some bad cipher text will coincidentally be the correct length to avoid this exception for AES.

In this scenario, we’ll most likely run into one of the other exceptions mentioned in this article instead.

3.2. IllegalBlockSizeException During Encryption

Now let’s look at this exception while we’re trying to encrypt the text “https://www.baeldung.com/“:

String plainText = "https://www.baeldung.com/";
byte[] plainTextBytes = plainText.getBytes();
		
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);
		
return cipher.doFinal(plainTextBytes);

As we saw above, for the AES algorithm to work, the number of bytes must be a multiple of 16, which our text isn’t. Therefore, running this code gives the same exception as above.

So can we only use AES to encrypt text that has 16, 32, 48… bytes?

What if we want to encrypt something that doesn’t have the correct number of bytes?

Well, this is where we’ll need to pad our data.

Padding data just means that we’re going to add extra bytes to the start, middle, or end of our text, thus ensuring that the data now has the correct number of bytes.

As with algorithm names and modes, there is a set list of permitted padding operations that we can use.

Fortunately, Java takes care of this for us, so we’re not going to go into details about how it works here.

All we have to do to fix this is set a padding operation, like PKCS #5, on our Cipher instance instead of specifying “NoPadding”:

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

Of course, the code that decrypts the text must also use the same padding operation.

3.3. Other Troubleshooting Tips

If we begin to get either a NoSuchAlgorithmException or a NoSuchPaddingException, we’ll need to check the Java docs to ensure that we’re using valid padding – and that our spelling has no typos.

If we’ve done this, then it may be worth checking that the document that we’re looking at matches the version of Java we’re working in, as the padding operations that are permitted can change between versions. The link provided in this article is for Java 8.

4. BadPaddingException: Given Final Block Not Properly Padded

The code will throw a BadPaddingException if it has a problem when dealing with padding, suggesting that it’s a problem with the padding that we’re using.

However, there can actually be several different problems that cause us to see this exception.

4.1. BadPaddingException Caused by Incorrect Padding

Let’s say that our text, “https://www.baeldung.com/“, is encrypted using ISO 10126 padding:

Cipher cipher = Cipher.getInstance("AES/ECB/ISO10126Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);

Then, if we try to decrypt it using different padding, say PKCS #5:

cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encryptionKey);

return cipher.doFinal(cipherTextBytes);

Our code would throw an exception:

javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
  at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
  at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
  at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
  at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
  at javax.crypto.Cipher.doFinal(Cipher.java:2168)

However, when we see this exception, padding is often not the root cause.

This is hinted at by a line in the exception above, “Such issues can arise if a bad key is used during decryption.”

So let’s see what else can cause a BadPaddingException.

4.2. BadPaddingException Caused by Incorrect Key

As the stack trace suggests, we may see this exception when we’re not using the correct encryption key to decrypt:

SecretKey encryptionKey = CryptoUtils.getKeyForText("BaeldungIsASuperCoolSite");
SecretKey differentKey = CryptoUtils.getKeyForText("ThisGivesUsAnAlternative");

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);

cipher.init(Cipher.DECRYPT_MODE, differentKey);

return cipher.doFinal(cipherTextBytes);

The above code throws a BadPaddingException rather than an InvalidKeyException because this is the point at which the code runs into a problem and can proceed no further.

This is probably the most common cause of this exception.

If we’re seeing this exception, then we must ensure that we’re using the correct key.

That means we must use the same key for encryption and decryption.

4.3. BadPaddingException Caused by Incorrect Algorithm

Given the above, this next one should be obvious, but it’s always worth checking.

We may see similar symptoms if we’re trying to decrypt using a different algorithm or algorithm mode to how the data was encrypted:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);

cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);

return cipher.doFinal(cipherTextBytes);

In the above example, the data is encrypted using a mode of CBC but decrypted using a mode of ECB, which isn’t going to work (in most cases).

Generally, our approach to resolving this exception would be to verify that each component of our decryption mechanism matches how the data was encrypted.

5. InvalidKeyException

An InvalidKeyException is normally an indication that we’ve set up our Cipher object incorrectly.

Let’s take a look at the most common causes.

5.1. InvalidKeyException: Parameters Missing

Some of the algorithms that we work with will require an Initialization Vector (IV).

An IV prevents the repetition of encrypted text and is thus required by some encryption modes like CBC.

Let’s try to init an instance of a Cipher that doesn’t have an IV set:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encryptionKey);
cipher.doFinal(cipherTextBytes);

If we run the above, then we’ll see the following stacktrace:

java.security.InvalidKeyException: Parameters missing
  at com.sun.crypto.provider.CipherCore.init(CipherCore.java:469)
  at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:313)
  at javax.crypto.Cipher.implInit(Cipher.java:805)
  at javax.crypto.Cipher.chooseProvider(Cipher.java:867)
  at javax.crypto.Cipher.init(Cipher.java:1252)
  at javax.crypto.Cipher.init(Cipher.java:1189)

Fortunately, this one is easily fixed, as we just need to init our Cipher with an IV:

byte[] ivBytes = new byte[]{'B', 'a', 'e', 'l', 'd', 'u', 'n', 'g', 'I', 's', 'G', 'r', 'e', 'a', 't', '!'};
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
cipher.init(Cipher.DECRYPT_MODE, encryptionKey, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(cipherTextBytes);

Note that the given IV must be the same as the IV used to encrypt the text.

One final note on our IV is that it must be of a certain length.

If we’re using CBC, our IV must be exactly 16 bytes long.

If we try to use a different number of bytes, we’ll get a very clear InvalidAlgorithmParameterException:

java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
  at com.sun.crypto.provider.CipherCore.init(CipherCore.java:525)
  at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:346)
  at javax.crypto.Cipher.implInit(Cipher.java:809)
  at javax.crypto.Cipher.chooseProvider(Cipher.java:867)

The fix is simply to ensure that our IV is 16 bytes long.

5.2. InvalidKeyException: Invalid AES Key Length: X Bytes

We’ll cover this one very quickly as it’s very similar to the above situation.

If we try to use a key of an incorrect length, then we’ll see a simple exception:

java.security.InvalidKeyException: Invalid AES key length: X bytes
  at com.sun.crypto.provider.AESCrypt.init(AESCrypt.java:87)
  at com.sun.crypto.provider.CipherBlockChaining.init(CipherBlockChaining.java:93)
  at com.sun.crypto.provider.CipherCore.init(CipherCore.java:591)

Our key must be 16 bytes too.

This is because Java typically only supports 128-bit (16-byte) encryption as default.

6. Conclusion

In this article, we saw a variety of exceptions that can occur when encrypting and decrypting text.

In particular, we saw cases where the exception may mention one thing, such as padding, but the root cause was actually something else, like an invalid key.

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)