1

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 Answers1

0

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.

Alexander
  • 1,232
  • 1
  • 15
  • 24
  • Thank you for your response, I'm using java iaik package to interact with this. However, when I see the code inside, I see getSlotList method only has this one. try { slotIDs = this.pkcs11Module.C_GetSlotList(tokenPresent); } catch (PKCS11Exception var5) { throw new iaik.pkcs.pkcs11.wrapper.PKCS11Exception(var5); } – Hoàng Ngô Nov 16 '22 at 02:00
  • Maybe there are exist another way and/or method to query slots list. Try to dive inside pkcs11Module.C_GetSlotList() for details. – Alexander Nov 16 '22 at 10:31