Search code examples
javakeystore

Java keystore load works fine on JDK 8 , but throws exception "stream does not represent a PKCS12 key store" on JDK 11


I am importing certificates in Java Keystore programmatically. I referred this SO post for the same.

Essentially from the post, the code works fine when compiled and run on Java 8. But on Java 11, keystore.load throws exception:

try {
         
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream storeInputStream = new FileInputStream(keystorePath);) {

            keystore.load(storeInputStream, storePassword); // storePassword is char[]
            // rest of the stuff
            
    }

Exception thrown by keystore.load:

java.io.IOException: stream does not represent a PKCS12 key store at org.bouncycastle.jcajce.provider.ProvPKCS12$PKCS12KeyStoreSpi.engineLoad(Unknown Source) at java.base/java.security.KeyStore.load(KeyStore.java:1479)

What could be the issue? I am assuming .jks files do not depend on Java version?


Solution

  • I figured out the issue. It was this line:

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

    Basically KeyStore.getDefaultType() returns jks in case of Java 8 while it returns pkcs12 in java 11.

    And since my keystore is jks type, in java 11 it failed to load when keystore was getting initialised by default to pkcs12.

    Changing this line to KeyStore.getInstance("jks") fixed the issue.