7

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.

Charlie
  • 8,530
  • 2
  • 55
  • 53

1 Answers1

32

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.

Charlie
  • 8,530
  • 2
  • 55
  • 53
  • Updating both KeyStore and Key password resolved similar issue we were having. – VinPro Mar 21 '18 at 15:09
  • 1
    I did the same thing as OP and had the same problem with Java 1.8. I then switched back to [old style](https://stackoverflow.com/a/43230396/1147688) and the problem was gone. Unfortunately *something* seem to whine about the use of that method, telling user to convert. **Don't!** – not2qubit Apr 02 '19 at 12:47
  • 1
    Came here because of Android Studio: it suggests me to transform key to PKCS12, and then comes up the same error of OP (and resulting in apk-generating failure). **Your answer REALLY SAVED MY DAY.** – Samuel T. Chou Nov 14 '20 at 06:49
  • The error message is really confusing. Thanks for the answer – Kislingk Jun 29 '21 at 21:33
  • This did not work for me. The moment I set the password of entry same as keystore, I got the invalid password . java.io.IOException: keystore password was incorrect and when I remove the password for the entry I get the same error as OP – Gagan Aug 06 '21 at 03:19
  • I extracted the keypair without a password and then created a new keystore and imported the keypair and that worked for me. thank you @Charlie – Gagan Aug 11 '21 at 19:31