Security Top

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

>> CHECK OUT THE COURSE

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/ISO10126Padding");

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/ECB/ISO10126Padding");
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.

As always, the example project is available over on GitHub.

Security bottom

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

>> CHECK OUT THE COURSE
Security footer banner
guest
0 Comments
Inline Feedbacks
View all comments