How to finalize SunPKCS11 Provider after it is initialized?

前端 未结 3 1999
庸人自扰
庸人自扰 2020-12-16 19:38

I have initialized the SunPKCS11 provider by:

Provider provider = new sun.security.pkcs11.SunPKCS11(\"path_to_pkcs11.cfg\");
Security.addProvider(provider);
         


        
3条回答
  •  抹茶落季
    2020-12-16 19:58

    Finally was able to find a solution. The Sun's Provider uses the Wrapper underneath. So the trick is to use the Sun's PKCS#11 Wrapper to get the current instance, and finalize it. Obviously this finalizing of the session feature is not exposed in the Provider. But there is a workaround, and it looks like this:

    public static void providerAndWrapperIssue() throws Exception
    {
        final String name = "ANY_NAME";
        final String library = "LOCATION OF THE TOKENS DLL/SO";
        final String slot = "SLOT NUMBER";
    
        // SUN PKCS#11 Provider -------------------------------------------
    
        StringBuilder builder = new StringBuilder();
        builder.append("name=" + name);
        builder.append(System.getProperty("line.separator"));
        builder.append("library=\"" + library + "\"");
        builder.append(System.getProperty("line.separator"));
        builder.append("slot=" + slot);
    
        ByteArrayInputStream bais = new ByteArrayInputStream(builder.toString().getBytes());
        Provider provider = new sun.security.pkcs11.SunPKCS11(bais);
        provider.setProperty("pkcs11LibraryPath", library);
        Security.addProvider(provider);
    
        KeyStore ks = KeyStore.getInstance("PKCS11");
        ks.load(null, null);
    
        Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements())
            System.out.println(aliases.nextElement());
    
        // ====================================
        // Solved it using the SUN PKCS#11 Wrapper
    
        PKCS11 pkcs11 = PKCS11.getInstance(((sun.security.pkcs11.SunPKCS11) provider).getProperty("pkcs11LibraryPath"), null, null, true);
        pkcs11.C_Finalize(PKCS11Constants.NULL_PTR);
    
        // ====================================
    
        // IAIK PKCS#11 Wrapper -------------------------------------------
    
        Module pkcs11Module = Module.getInstance(library, false);
        pkcs11Module.initialize(null);
    
        Slot[] slots = pkcs11Module.getSlotList(true);
    
        Session session = slots[0].getToken().openSession(true, true, null, null);
        session.login(Session.UserType.USER, "".toCharArray());
    
        session.logout();
        session.closeSession();
    
        slots[0].getToken().closeAllSessions();
    
        pkcs11Module.finalize(null);
    }
    

提交回复
热议问题