Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BadPaddingException loading p12 keystore

Tags:

java

When executing the following code:

KeyStore ks = KeyStore.getInstance(storeType);
ks.load(new FileInputStream(keyStore), storePassword.toCharArray());

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyPassword.toCharArray());

I get an exception:

java.security.UnrecoverableKeyException: Get Key failed: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

This was originally from a JKS keystore converted to a PKCS12 keystore using keytool. I tried creating a new fresh PKCS12 keystore but no luck.

like image 215
Charlie Avatar asked Oct 12 '17 04:10

Charlie


1 Answers

JKS supports using two passwords, one for the store and one for the key inside. PKCS12 uses the same password for both. When using the keytool, you'll get a warning about this.

When migrating to the new keystore, the code will likely continue using one password for the keystore, and another (different) password for the key, though now that won't work.

Java 9 gives a much better exception message around this indicating it might arise from a bad key during decryption.

In this case, make sure to pass in a key password that matches the store password.

like image 148
Charlie Avatar answered Oct 18 '22 00:10

Charlie