javakeystorejksjava-securitycacerts

Java cacerts of type JKS is being loaded while the KeyStore.getDefaultType() is still PKCS12


cacerts, the default truststore of Java is of type JKS in OpenJDK 17. So while trying to load it, I have KeyStore.getDefaultType() set to PKCS12 by default and I am still able to load them.

I've tried following approach to load them and there were no issues,

import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;

public class MyClass {
    public static void main(String[] args) throws Exception {
        String defaultType = KeyStore.getDefaultType();
        System.out.println("Default Keystore Type: " + defaultType);
        
        String javaHome = System.getProperty("java.home");
        String cacertsPath = javaHome + "/lib/security/cacerts";
        KeyStore trustStore = KeyStore.getInstance(defaultType);
        
        try (FileInputStream fis = new FileInputStream(cacertsPath)) {
            trustStore.load(fis, "changeit".toCharArray());
        }
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);

        System.out.println("Loaded truststore with " + trustStore.size() + " entries");
    }
}

I was expecting an error to be thrown since the types are mismatching. But that isn't happening. Why is it so?

Find snippet for the same code here

Snippet showing the type of cacerts file can be viewed here


Solution

  • In order to make this thing work as expected we can set the JVM arg,
    keystore.type.compat=false

    By default the value is set to true and can be found at $JAVA_HOME/conf/security/java.security

    Controls compatibility mode for JKS and PKCS12 keystore types.

    When set to 'true', both JKS and PKCS12 keystore types support loading keystore files in either JKS or PKCS12 format. When set to 'false' the JKS keystore type supports loading only JKS keystore files and the PKCS12 keystore type supports loading only PKCS12 keystore files.

    keystore.type.compat=true