java 中的 pkcs11 工具生成的密钥未加载到 pkcs11 密钥库中

pkcs11-tool generated keys in java are not getting loaded into pkcs11 keystore

我在尝试从 java pkcs11 密钥库获取私钥时看到空指针异常,而私钥是由 pkcs11-tool 生成的。如果密钥是使用 keytool 生成的,则此方法可以正常工作。我也可以列出来自 pkcs11-tool 的密钥,但不能来自 keytool。除了 keytool 之外,导入或生成密钥以便它们对 java pkcs11 密钥库可见的正确方法是什么?

生成密钥:

pkcs11-tool --module /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so -l --pin <pin> --keypairgen --key-type rsa:2048 --label jtest

从 java 加载并访问密钥(代码段):

    String configName = "/tmp/pkcs11.cfg";
    Provider p = new SunPKCS11(configName);
    Security.addProvider(p);

    char[] pin = "<pin>".toCharArray();
    KeyStore keyStore = KeyStore.getInstance("PKCS11", p);
    keyStore.load(null, pin);
    PrivateKeyEntry privateKeyEntry =
                    (PrivateKeyEntry)keyStore.getEntry("jtest", null);
    PrivateKey privateKey = privateKeyEntry.getPrivateKey(); 

在尝试获取上面的私钥时看到异常。

Keytool 在生成密钥条目时会自动生成 self-signed 证书,而 PKCS#11 允许在没有相应证书的情况下创建密钥对。

Java 密钥库API 简单地忽略没有证书的密钥对条目。这就是为什么 keytool -list ... 不显示使用 pkcs11-tool 创建的条目的原因。如果您查看 Oracle PKCS#11 guide,尤其是限制,它会显示:

Once a private key and certificate have been matched (and its certificate chain built), the information is stored in a private key entry with the CKA_LABEL value from end entity certificate as the KeyStore alias.

...

Any private key or certificate object not part of a private key entry or trusted certificate entry is ignored.

因此,当您调用 keyStore.getEntry("jtest", null); 时,它找不到匹配的键条目,这会导致下一行出现 NPE。