Can't access to sun.security.pkcs11.SunPKCS11 in Java 11

Viewed 710

I try to write Java code to get the private key in my USB token and I get the following error:

return new SunPKCS11(tmpConfigFile.getAbsolutePath());

'SunPKCS11(sun.security.pkcs11.Config)' is not public in 'sun.security.pkcs11.SunPKCS11'. Cannot be accessed from outside package

Thank a lot !

2 Answers

It's been a while when this question has been asked, but for all with the same question, this might still help.

Java 11 changed the way PKCS#11-keystores are accessed as described in the updated PKCS#11 Reference Guide for Java 11. Instead of initializing via constructor you're supposed to get the Provider via Security.getProvider and then call configure. An example can be found in the reference guide:

String configName = "/opt/bar/cfg/pkcs11.cfg";
Provider p = Security.getProvider("SunPKCS11");
p = p.configure(configName);

There is multiple ways :

  1. Create a new class that is in sun.security.pkcs11 package, and create the object for you, like that:
package sun.security.pkcs11;

public class MyClass {

   public static SunPKCS11 createPKCS(Config config) {
      return new SunPKCS11(config);
   }
}
  1. Use reflection
public SunPKCS11 create(Config config) {
   Constructor<?> pkcsCons = SunPKCS11.class.getConstructor(Config.class);
   pkcs.setAccessible(true);
   return pkcsCons.newInstance(config);
}
  1. Check this documentation more speficially the 2.2 paragraph
Related