2
Provider p = new SunPKCS11(configName);
char[]pin = "****".toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS11", p);
ks.load(null, this.pin);

if (-1 == Security.addProvider(this.p)) {
    throw new RuntimeException("Could not add security provider");
}

How can I reload the keys ? Every time I run the code, I get the same instance of a KeyStore object, so the same keys.

bgn2010
  • 21
  • 3

2 Answers2

0

Here, I see that you are not loading any keystore eg no JSK file. Please see the below sample code

File f = new File(kStoreName);
if(f.exists() && !f.isDirectory()){
   try(FileInputStream fis = new FileInputStream(f.getAbsolutePath())){
     ks.load(fis, storePassword.toCharArray());
  }
}
  • The question mentions PKCS11 KeyStore, which is a hardware token based. Your answer mentions `JKS`, which is a file based KeyStore (soft). It will not work for PKCS11 KeyStore. – always_a_rookie Apr 10 '19 at 15:09
0

Basically the Sun Provider implementation caches the Provider instance. Hence you are getting the instance in your application. One way to overcome this is to manually finalize the PKCS11 provider. You can find it in my other answer here.

Add a property to your provider instance p:

p.setProperty("pkcs11LibraryPath", library);

And then finalize the PKCS provider manually before fetching the keys:

PKCS11 pkcs11 = PKCS11.getInstance(((sun.security.pkcs11.SunPKCS11) provider).getProperty("pkcs11LibraryPath"), null, null, true);
pkcs11.C_Finalize(PKCS11Constants.NULL_PTR);
always_a_rookie
  • 4,515
  • 1
  • 25
  • 46