1

我愿意使用存储在 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();

可能是我错过了什么?

4

1 回答 1

2

你应该改变

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

keyStore = KeyStore.getInstance("PKCS11");

来自意大利的问候

于 2020-01-13T14:07:01.303 回答