Search code examples
javainputstreamkeystorefileinputstream

difference between FileInputStream and ClassLoader.getSystemResourceAsStream


Weird problem and I verified it is reading the same file.

This does not work:

keystore = KeyStore.getInstance("PKCS12");
InputStream inputStream = ClassLoader.getSystemResourceAsStream("keystores/active.pfx");
keystore.load(inputStream, "the_password".toCharArray());

This, however, does work:

keystore = KeyStore.getInstance("PKCS12");
InputStream inputStream = new FileInputStream(new File("src/main/resources/keystores/active.pfx"));
keystore.load(inputStream, "the_password".toCharArray());

I get the following error:

DER length more than 4 bytes: 111

It's that change of the input stream and I can't figure out what the difference is. I triple-checked the file to make sure it was using the same file. Why is Java treating these streams differently? If I figure out that, I can probably figure out how to fix the problem.


Solution

  • The two approaches are not reading the exact same file. The resource code reads it from the JAR file or wherever the classes got compiled to. Clearly the file got corrupted somehow during the build process.