sunPKCS11 provider can be loaded either programmatically or statically.
To add statically to the list of java security providers, append to java.security file.
security.provider.n=sun.security.pkcs11.SunPKCS11 /opt/pkcs/pkcs11.cfg
And get the provider using
Provider p = Security.getProvider("SunPKCS11-pkcs11Test");
where pkcs11.cfg contains the PKCS11 library, token slot and name.
name = pkcs11Test
library = /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so
slot = 0
To add programmatically from java:
// Set up the Sun PKCS 11 provider
String configName = "/tmp/pkcs11.cfg";
Provider p = new SunPKCS11(configName);
Security.addProvider(p);
Load the key store.
char[] pin = "pin".toCharArray();
KeyStore keyStore = KeyStore.getInstance("PKCS11", p);
keyStore.load(null, pin);
Generate key pair.
// Generate the keypair
SecureRandom sr = new SecureRandom();
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, sr);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey pk = keyPair.getPrivate();
Store the keys in SoftHSM token.
// Set the entry in keystore
keyStore.setKeyEntry("<key id>", pk, "pin".toCharArray(), chain);
//store it
keyStore.store(null);