Android

Android 12 (API level 31): Key size must be either 128, 192, or 256 bits.

Android 12 introduced some breaking changes on its security stack. Google is slowly dropping Bauncy Castle java security stack in favor of Conscrypt security java layer.

At one of my clients I had some strange situation: on the latest Android 12 (API level 31) testing, some apps stop working and start throwing following exception:

Key size must be either 128, 192, or 256 bits

After reading some documentation, e.g. https://developer.android.com/about/versions/12/behavior-changes-all#bouncy-castle and observing the code, I found out that application is generating AES secret keys of 384 bits in size. Obviously, Bauncy Castle java security provider handle this situation, but Conscrypt is failing at runtime.

Let’s take a look what is going on.

The problem

I created simple Android Java application which generates AES key of 384 bits in size, and checked what is going on Android 12 (API 31) and on Androids older then 12 (API level <31).

Here is my simple code extract:

The output on Android 12 (API 31) compared with some older Android API level was different, as depicted below:

android 12 and older devices and AES key generation problem

I isolated the problem, so let’s start working on solution!

The solution

I need quick and easy solution, which will be backward compatible. Anyway, solution is quite straightforward: I created 3 secret keys of 128 bits (128+128+128 = 384) and combine them (or 256+128 = 384, or 192+192 = 384).

My quick and dirty solution is something like:

Finally, my tests on different Android API devices/emulators are working just as expected:

android 12 and older devices and AES key generation fix

If useful for someone, here s the complete code:

Summay

If you have java Android app which generates AES keys different as 128, 192 or 256 in size – or if your app is using 512 key size – or you initialize Galois/Counter Mode (GCM) ciphers using a size other than 12 byte: your app will not work or it will behave strangely on Android 12 devices.

This is due to braking changes on Android 12 java security layer. To be more precise, Google is replacing Bauncy Castle security layer with Conscrypt.

I really hope you don’t have such problems, but if you do, start fixing them as soon as possible!

Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.