为了PKCS#11
在 java 中使用,您需要提供一个配置文件,您至少在其中指定库和名称参数。在此参数中,您必须为令牌和任意标识符指定本机库的路径。此外,您可以添加更多参数,但它们是可选的,您可以查看java pkcs#11 参考指南。我给你一个代码示例来实例化 a PKCS#11
:
// create configuration
String pkcs11nativeLibrary = "/path_to_native_library/library.so";
String pkcs11ConfigSettings = "name = mySmartCard\n" + "library = " + pkcs11nativeLibrary;
byte[] pkcs11ConfigBytes = pkcs11ConfigSettings.getBytes();
final ByteArrayInputStream confStream = new ByteArrayInputStream(pkcs11ConfigBytes);
// instantiate the provider with your config
SunPKCS11 pkcs11Provider = new SunPKCS11(confStream);
Security.addProvider(pkcs11Provider);
// get the keystore
Char[] pkcs11Password = "your_password".toCharArray();
KeyStore myPKCS11KS = KeyStore.getInstance("PKCS11", pkcs11Provider );
myPKCS11KS.load(null, pkcs11Password);
在示例中,我直接输入了 pkcs11 密码,但是当您尝试从某个客户端加载 PKCS#11 时,您必须动态获取密码才能这样做,您可以将密钥存储实例更改为:
// YourCallbackHandler must implements javax.security.auth.callback.CallbackHandler
KeyStore.CallbackHandlerProtection cbhp = new KeyStore.CallbackHandlerProtection(new YourCallbackHandler());
KeyStore.Builder builder = KeyStore.Builder.newInstance("PKCS11", pkcs11Provider, cbhp);
KeyStore myPKCS11KS = builder.getKeyStore();
希望这可以帮助,