[当我尝试将secp256k1私钥导入到我的CloudHSM实例时,出现错误“ java.security.InvalidKeyException:密钥是CaviumKey的实例,无法导入。”导入secp256r1私钥可以正常工作。
我正在使用提供的示例作为指导(https://github.com/aws-samples/aws-cloudhsm-jce-examples),并且似乎exportKey方法不会将密钥转换为privateKey,而是返回CaviumKey(我已链接到下面方法中的行)。
/**
* 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实例的PrivateKey,当尝试通过Cavium库导入到HSM时抛出错误。
没有人知道为什么会发生这种情况或我该如何解决?
代替EC,您是否尝试使用CaviumKeyAttributes.KEY_TYPE_ECDSA?