java - 从 hyperledger ca 生成的私钥文件中获取 java.security.PrivateKey
问题描述
使用hyperledger-fabric-ca工具我得到了如下的私钥
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrECQDuXL87QJKYDO
O/Z1TT+vzVPqF3106wT75dJF5OqhRANCAASsFuneE46/9JmUJCiQ14zWDKcFn6TL
kYl6mirTXefU7yYglu5hmehU0pD/PKKLkoTLNbPLn5RMdUe8aum3N1sZ
-----END PRIVATE KEY-----
默认情况下,该软件使用ecdsa-with-SHA256
( prime256v1
) 签名算法
在我的 java 应用程序中,我需要有基于上述私钥的 java.security.PrivateKey 实例。
我试过以下代码
public static void main(String[] args) throws Exception {
String privateKeyString = "-----BEGIN PRIVATE KEY-----\n" +
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrECQDuXL87QJKYDO\n" +
"O/Z1TT+vzVPqF3106wT75dJF5OqhRANCAASsFuneE46/9JmUJCiQ14zWDKcFn6TL\n" +
"kYl6mirTXefU7yYglu5hmehU0pD/PKKLkoTLNbPLn5RMdUe8aum3N1sZ\n" +
"-----END PRIVATE KEY-----\n";
String privateKeyContent = privateKeyString.replaceAll("\\n|-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----", "");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyContent.getBytes());
KeyFactory factory = KeyFactory.getInstance("EC");
PrivateKey privateKey = factory.generatePrivate(spec);
}
但我得到
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
at sun.security.ec.ECKeyFactory.engineGeneratePrivate(ECKeyFactory.java:169)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
at QueryApp.main(QueryApp.java:36)
Caused by: java.security.InvalidKeyException: invalid key format
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:330)
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356)
at sun.security.ec.ECPrivateKeyImpl.<init>(ECPrivateKeyImpl.java:73)
at sun.security.ec.ECKeyFactory.implGeneratePrivate(ECKeyFactory.java:237)
at sun.security.ec.ECKeyFactory.engineGeneratePrivate(ECKeyFactory.java:165)
... 2 more
解决方案
您必须对内容进行 base64 解码,例如
String privateKeyContent = privateKeyString.replaceAll("\\n|-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----", "");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyContent));
KeyFactory factory = KeyFactory.getInstance("EC");
推荐阅读
- flutter - Dart Flutter:使用三元运算符同时设置两个变量
- mongodb - 在 Symfony Monolog 中使用 MongoDB 会导致错误
- javascript - 我正在尝试从不同的项目和产品中获取总价格*数量。输入。如何仅控制已更改的数组?
- python - Django REST:TypeError:“语言”类型的对象不是 JSON 可序列化的
- .htaccess - 为带有 HTML 5 历史模式的 Progressive Web App 添加 HTTPS 重定向
- java - if (not null && not null) Java 函数式编程
- linux - linux shell:连接指令和文件
- c - C中两个数组的交集问题
- webgl - WebGL 模型框架和世界框架的关系
- android - Android:使用 Gmail api 从服务中读取 Gmail 邮件正文