PKCS11 does not recognize new slot created in softhsm in runtime

496 views Asked by At

I have a piece of code to import key and certificate into hsm using java. The problem is that when I run the java back-end to execute that api, it is ok when using the slots which were created before. However the problem here, when I create new slot at that time and try to execute the api for that slot, I received the message that show the slot id not found.

How do I achieve the result without re-running the code ? Here is what I am doing

public void importCertAndPk(String pin, String slotId, String alias, InputStream p12File) {
    Provider p = getProvider(slotId);
    // Load the key store
    KeyStore ks = getKeyStore(p, pin);
    BouncyCastleProvider provider = new BouncyCastleProvider();
    // Get pk and cert from p12 file
    KeyStore pkcs12KeyStore = KeyStore.getInstance("pkcs12", provider.getName());
    pkcs12KeyStore.load(p12File, System.getenv("P12_PASS").toCharArray());
    String pkcs12Alias = pkcs12KeyStore.aliases().nextElement();
    PrivateKey pk = (PrivateKey) pkcs12KeyStore.getKey(pkcs12Alias, null);
    Certificate[] chain = pkcs12KeyStore.getCertificateChain(pkcs12Alias);
    ks.setKeyEntry(alias, pk, pin.toCharArray(), chain);
}

When I re-run the back-end code again, it works

1

There are 1 answers

2
Alexander On BEST ANSWER

Please look at PKCS#11 specification section 5.5:

Furthermore, the set of slots accessible through a Cryptoki library is checked at the time that C_GetSlotList, for list length prediction (NULL pSlotList argument) is called. If an application calls C_GetSlotList with a non-NULL pSlotList, and then the user adds or removes a hardware device, the changed slot list will only be visible and effective if C_GetSlotList is called again with NULL

You must re-query slot's list.