我已通过以下方式初始化 SunPKCS11 提供程序:
Provider provider = new sun.security.pkcs11.SunPKCS11("path_to_pkcs11.cfg");
Security.addProvider(provider);
然后我使用这个提供程序来初始化 KeyStore 以使用密钥进行密码操作。
KeyStore ks = KeyStore.getInstance("PKCS11", provider);
ks.load(null, "password".toCharArray());
完成密码操作后,我应该如何使用 PKCS11 令牌完成会话?
我已经尝试删除提供程序,但它没有工作。
Security.removeProvider("sunPCKS11ProviderName");
下次我尝试与令牌通信时,我从令牌CKR_CRYPTOKI_ALREADY_INITIALIZED中得到这个异常
更新:
我努力了
sun.security.pkcs11.SunPKCS11.logout();
但它也没有用。
我有一个用例,我必须同时使用 PKCS#11 Wrapper 和 Provider。为了能够使用包装器,我必须最终确定提供程序,否则CKR_CRYPTOKI_ALREADY_INITIALIZED
当包装器尝试与令牌通信时,令牌会引发错误。
更新代码:
我正在使用 Sun 的 PKCS#11 Provider 和 IAIK 的 PKCS#11 Wrapper。
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);
Security.addProvider(provider);
KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(null, null);
Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements())
System.out.println(aliases.nextElement());
// IAIK PKCS#11 Wrapper -------------------------------------------
Module pkcs11Module = Module.getInstance(library, false);
pkcs11Module.initialize(null); <-- Exception here.
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);
}
由于 Sun 的提供商没有注销和关闭会话,因此 IAIK 无法访问令牌。并且 Java 的Keystore
api 没有注销的方法。