【问题标题】:PKCS11Exception: CKR_MECHANISM_INVALID How to integrate Java and PKCS11 and GCP Cloud KMS?PKCS11Exception: CKR_MECHANISM_INVALID 如何集成 Java 和 PKCS11 和 GCP Cloud KMS?
【发布时间】:2022-10-18 22:12:29
【问题描述】:

我正在尝试使用 GCP Cloud KMS 来建立 mTLS。为此,我正在准备集成 Java + JCE + PKCS11 + Cloud KMS 集成库 + GCP Cloud KMS 的 PoC。 堆:

结果我有一个例外:

Private key:  SunPKCS11-KmsHSM RSA private key, 3072 bitstoken object, sensitive, unextractable)
I20220812 18:55:30.725561    12 logging.cc:137] returning 0x70 from C_DecryptInit due to status INVALID_ARGUMENT: at crypter_ops.cc:33: mechanism 0x1 is not valid for operation decrypt [type.googleapis.com/kmsp11.StatusDetails='CK_RV=0x70']
I20220812 18:55:30.726071    12 logging.cc:137] returning 0x70 from C_DecryptInit due to status INVALID_ARGUMENT: at crypter_ops.cc:33: mechanism 0x1 is not valid for operation decrypt [type.googleapis.com/kmsp11.StatusDetails='CK_RV=0x70']
java.security.InvalidKeyException: init() failed
    at sun.security.pkcs11.P11RSACipher.implInit(P11RSACipher.java:239)
    at sun.security.pkcs11.P11RSACipher.engineInit(P11RSACipher.java:168)
    at javax.crypto.Cipher.implInit(Cipher.java:805)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:867)
    at javax.crypto.Cipher.init(Cipher.java:1252)
    at javax.crypto.Cipher.init(Cipher.java:1189)
    at engsec.cmds.EncryptKMS.run(EncryptKMS.java:73)
    at engsec.App.main(App.java:34)
Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_MECHANISM_INVALID
    at sun.security.pkcs11.wrapper.PKCS11.C_DecryptInit(Native Method)
    at sun.security.pkcs11.P11RSACipher.initialize(P11RSACipher.java:323)
    at sun.security.pkcs11.P11RSACipher.implInit(P11RSACipher.java:237)
    ... 7 more

代码如下:

            KeyStore ks = KeyStore.getInstance("PKCS11");
            ks.load(null, null);

            Key privateKey = ks.getKey(
                    PRIVATE_KEY_ALIAS,
                    null
            );

            Cipher cipher2 = Cipher.getInstance("RSA");
            cipher2.init(
                    Cipher.DECRYPT_MODE,
                    privateKey
            );
            byte[] clearText = cipher2.doFinal(cipherBytes);

            System.out.println("Decrypted value: ", new String(clearText));

如何修复异常? 是否可以集成 Java 生态系统和 Cloud KMS 来建立 mTLS? 谢谢!

【问题讨论】:

    标签: java google-cloud-platform pkcs#11 google-cloud-kms sunpkcs11


    【解决方案1】:

    假设PRIVATE_KEY_ALIAS处的密钥是指Cloud KMS中的签名密钥(即具有ASYMMETRIC_SIGN用途的密钥),则不能用于解密。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-08
      • 2021-04-11
      • 2020-08-13
      • 1970-01-01
      • 2014-12-25
      • 2021-07-01
      • 2019-03-10
      • 1970-01-01
      相关资源
      最近更新 更多