Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to read certificate from KeyStore when running Unit Test

For some reason a KeyStore I load in a Unit Test appears to be empty, and I have no idea why.

I have a keystore file with a certificate in it here: src/test/resources/public-keystore-name

So, running this command in a terminal:

../src/test/resources$ keytool -list -keystore public-keystore-name -storetype PKCS12

I get the following output:

Keystore type: PKCS12
Keystore provider: SunJSSE

Your keystore contains 1 entry

aliasname, May 22, 2015, trustedCertEntry, 
Certificate fingerprint (SHA1): 4E:87:CF:EF:FC:E1:37:63:36:E0:26:0C:1E:B3:65:BB:48:3A:83:1A

In my unit test, I can load and initiate a KeyStore from this file alright, but I cannot fetch the certificate that I have stored in it. The certificate has alias "aliasname", and password "password".

   @Test
   public void testUtil() throws Exception {

     KeyStore publicKS = KeyStore.getInstance("PKCS12");

     File publicKeyStoreFile = FileUtils.getFile("src/test/resources/public-keystore-name");
     FileInputStream fisPublic = new FileInputStream(publicKeyStoreFile);

     publicKS.load(fisPublic, "password".toCharArray());

     Certificate cert = publicKS.getCertificate("aliasname");

     System.out.println("Cert is: " + cert);
   }

Will always print: "Cert is: null"

Why is the KeyStore empty in this Unit Test? (looking for aliases with Keystore.aliases() will return an empty set).

like image 480
Lars Andren Avatar asked Nov 10 '22 12:11

Lars Andren


1 Answers

The KeyStore was created using BouncyCastle-stuff, so that needed to go into the setting up of this KeyStore:

...
    KeyStore publicKS = KeyStore.getInstance("PKCS12", "BC");
...

"BC" is the shorthand for BouncyCastle, and can be used after running:

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

I guess the default KeyStore is probably some Java standard?

like image 151
Lars Andren Avatar answered Nov 14 '22 22:11

Lars Andren