无法验证加密私钥

问题描述 投票:0回答:1

我有以下背景:

我使用

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 365 -nodes
生成密钥和证书文件。

然后我使用

openssl pkcs8 -in key.pem -out key-encrypted.pem -topk8
来加密我的私钥。

最后,我使用

openssl req -x509 -key key-encrypted.pem -out cert-encrypted.pem -sha256 -days 365 -nodes
为我的加密私钥生成证书文件。

该代码适用于

key.pem
cert.pem
,但对于
key-encrypted.pem
cert-encrypted.pem
有问题。

到这行生成私钥的时候,显示错误

java.security.InvalidKeyException: IOException : DerValue.getBigIntegerInternal, not expected 48

我加载我的证书文件并创建 X509Certificate 对象,如下所示:

byte[] certData = Files.readAllBytes(certPath);
InputStream st = new ByteArrayInputStream(certData)
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
certificate = (X509Certificate) certFactory.generateCertificate(st);

然后我加载我的私钥文件,如下所示:

List<String> keys = Files.readAllLines(keyPath);
//I have removed the first and last line of the key content:
//-----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY----- lines
String key = String.join("", keys);

//Parse it into PKCS8
byte[] decoded = Base64.decodeBase64(key);
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(decoded);

//Now I use kf to generate private key
PrivateKey pk = kf.generatePrivate(ks);

//Then I use the following code to verify
byte[] challenge = new byte[10000];
ThreadLocalRandom.current().nextBytes(challenge);

Signature s = Signature.getInstance("SHA256withRSA");
s.initSign(pk);
s.update(challenge);

byte[] sign = s.sign();
s.initVerify(certificate.getPublicKey());
s.update(challenge);
s.verify(sign);
java encryption openssl rsa
1个回答
0
投票

PKCS8EncodedKeySpec
仅支持inner PKCS#8结构。此类不直接支持加密的 PKCS#8。然而,有 EncryptedPrivateKeyInfo 可以做到这一点。

您可以在此处找到有关如何使用该课程的更多信息。请注意,现在应该使用 PBE2(即 PBKDF2)来进行密钥派生,所以应该没问题。

© www.soinside.com 2019 - 2024. All rights reserved.