1

I am loading the key store as follows:

try
{
  ks = KeyStore.getInstance("BKS", "BC"); 
  ks.load(ksStream, ksPass);
}
catch (IOException e)
{
  if (e.getCause() instanceof UnrecoverableKeyException)
    System.err.println("Wrong password!");
}

The problem is that the cause of the exception is not set by bouncy castle (it's null).

How to fix this?

zomega
  • 1,538
  • 8
  • 26

1 Answers1

1

It is not possible to know for certain if the failure to load the BKS keystore was caused by an incorrect password or by data corruption or both. The reason for this uncertainty is because there is no field in the BKS format that is exclusively for testing the correctness of the password. All that is available is a Message Authentication Code(MAC) calculated over the body of the keystore. If the MAC check succeeds then you can have confidence that everything is correct including the password. If the MAC fails, then the problem could be the password or data corruption, or both.

The use of an IOException to convey this problem is a poor choice and is probably a vestige of the original design by Sun engineers. Since Bouncycastle is merely an engine in the JCE framework they must comply with the signature for KeyStore.load() including the exception specs. The version of Bouncycastle I looked at includes a detail message "KeyStore integrity check failed." in the exception that can at least identify the exception as caused by a MAC failure as opposed to an actual I/O problem.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
  • There is no reliable way to check for invalid password exception. In my testing, I have encountered at least 4 different exception types (`org.bouncycastle.crypto.io.InvalidCipherTextIOException`, `java.io.UTFDataFormatException`, `java.io.IOException`, `java.io.EOFException`) but I wouldn't be surprised to see more, possibly even `OutOfMemoryError` given how the reading code works (reading random data with `readUTF`). – Darkyen Feb 03 '23 at 14:59