没有安装的提供程序支持此密钥:使用SoftHSM2 AES密钥时,sun.security.pkcs11.P11Key $ P11SecretKey

时间:2019-02-09 08:24:06

标签: java encryption aes softhsm

我愿意使用softHSM2软件中存储的AES密钥对数据进行加密/解密。

我正在使用以下代码创建密钥:

    String configName = "C:\\SoftHSM2\\etc\\pkcs11.cfg";

    cipher = Cipher.getInstance("AES");

    Provider p = new SunPKCS11(configName);
    if (-1 == Security.addProvider(p)) {
        throw new RuntimeException("could not add security provider");
    }

    // Load the key store
    char[] pin = "123456789".toCharArray();
    keyStore = KeyStore.getInstance("PKCS11", p);
    keyStore.load(null, pin);

    SecretKeySpec secretKeySpec = new 
    SecretKeySpec("0123456789ABCDEF".getBytes(), "AES");
    Key key = new SecretKeySpec(secretKeySpec.getEncoded(), "AES");
    keyStore.setKeyEntry("AESKey1", key, "123456789".toCharArray(), null);
    keyStore.store(null);

这是pkcs11.cfg

name = SoftHSM2
library = c:\SoftHSM2\lib\softhsm2-x64.dll 
slotListIndex = 1

我的密钥正确添加,这是输出:

AESKey1: SunPKCS11-SoftHSM2 AES secret key, 16 bits (id 4, token object, not sensitive, unextractable)

现在,我想使用此密钥进行加密/解密。这是要加密的代码:

        myKey = keyStore.getKey("AESKey1", "123456789".toCharArray()); 
        System.out.println("Using key: "+myKey.toString());        
        byte[] plainTextByte = text.getBytes();                 
        cipher.init(Cipher.ENCRYPT_MODE, myKey);
        byte[] encryptedByte = cipher.doFinal(plainTextByte);
        Base64.Encoder encoder = Base64.getEncoder();
        encryptedText = encoder.encodeToString(encryptedByte);

和解密功能:

        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptedTextByte = decoder.decode(text);
        cipher.init(Cipher.DECRYPT_MODE, keyStore.getKey("AESKey1", "1234".toCharArray())); 
        byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
        decryptedText = new String(decryptedByte);

但是我提出了以下异常:

Using key: SunPKCS11-SoftHSM2 AES secret key, 16 bits (id 10, token object, not sensitive, unextractable)
java.security.InvalidKeyException: No installed provider supports this key: 
sun.security.pkcs11.P11Key$P11SecretKey
    at javax.crypto.Cipher.chooseProvider(Cipher.java:888)
    at javax.crypto.Cipher.init(Cipher.java:1229)
    at javax.crypto.Cipher.init(Cipher.java:1166)

 Encrypted Text After Encryption: 
java.security.InvalidKeyException: No installed provider supports this key: sun.security.pkcs11.P11Key$P11SecretKey
at javax.crypto.Cipher.chooseProvider(Cipher.java:888)
at javax.crypto.Cipher.init(Cipher.java:1229)

两个cipher.init调用都引发一个异常,请注意,如果我正在这样创建AES密钥(在softHSM2中),则此代码可以正常工作:

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); // block size is 128bits
        SecretKey secretKey = keyGenerator.generateKey();

我可能缺少什么吗?

1 个答案:

答案 0 :(得分:0)

您应该更改

keyStore = KeyStore.getInstance("PKCS11", p);

keyStore = KeyStore.getInstance("PKCS11");

来自意大利的问候