无法使用 Amazoun CloudHSM Java 库存储 secp256k1 生成的私钥



当我尝试将secp256k1私有密钥导入我的CloudHSM实例时,出现错误"java.security.InvalidKeyException:密钥是CaviumKey的实例,无法导入。导入 secp256r1 私钥工作正常。

我使用提供的示例作为指导(https://github.com/aws-samples/aws-cloudhsm-jce-examples(,似乎 exportKey 方法不会将密钥转换为私钥,而是返回 CaviumKey(我已经链接到下面方法中的行(。

https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/KeyUtilitiesRunner.java#L278

/**
 * Export an existing persisted key.
 * @param handle The key handle in the HSM.
 * @return Key object
 */
private static Key exportKey(long handle) {
    try {
        byte[] keyAttribute = Util.getKeyAttributes(handle);
        CaviumKeyAttributes cka = new CaviumKeyAttributes(keyAttribute);
        System.out.println(cka.isExtractable());
        byte[] encoded = Util.exportKey( handle);
        if(cka.getKeyType() == CaviumKeyAttributes.KEY_TYPE_AES) {
            Key aesKey = new SecretKeySpec(encoded, 0, encoded.length, "AES");
            return aesKey;
        }
        else if(cka.getKeyType() == CaviumKeyAttributes.KEY_TYPE_RSA && cka.getKeyClass() == CaviumKeyAttributes.CLASS_PRIVATE_KEY) {
            PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(encoded));
            return privateKey;
        }
        else if(cka.getKeyType() == CaviumKeyAttributes.KEY_TYPE_RSA && cka.getKeyClass() == CaviumKeyAttributes.CLASS_PUBLIC_KEY) {
            PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encoded));
            return publicKey;
        } else if(cka.getKeyType() == CaviumKeyAttributes.KEY_TYPE_EC && cka.getKeyClass() == CaviumKeyAttributes.CLASS_PRIVATE_KEY) {
            PrivateKey privateKey = KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(encoded));
            return privateKey;
        }
        else if(cka.getKeyType() == CaviumKeyAttributes.KEY_TYPE_EC && cka.getKeyClass() == CaviumKeyAttributes.CLASS_PUBLIC_KEY) {
            PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(encoded));
            return publicKey;
        }
    } catch (BadPaddingException | CFM2Exception e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

此函数返回一个私钥,该私钥仍然是 CaviumKey 的实例,在尝试通过 Cavium 库导入 HSM 时会引发错误。

有没有人知道为什么会发生这种情况或我如何解决这个问题?

你试过用CaviumKeyAttributes.KEY_TYPE_ECDSA而不是 EC?

相关内容

  • 没有找到相关文章

最新更新