我有如下要求:
- 创建一个自签名(比如CA证书)并保存证书和私钥到文件
- 加载CA证书(在步骤1中创建)及其私钥
- 创建结束使用中加载的CA证书和私钥签名的证书步骤2
我的私钥存储到如下文件中:
public static void writePrivateKey(PrivateKey privateKey, OutputStream os) throws IOException
{
BufferedOutputStream bos = new BufferedOutputStream(os);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
privateKey.getEncoded());
bos.write(pkcs8EncodedKeySpec.getEncoded());
bos.close();
}
我的私钥加载如下:
public PrivateKey loadPrivatekey(InputStream privateKeyInputStream)
throws InvalidKeySpecException, NoSuchAlgorithmException, IOException
{
return KeyFactory.getInstance(algorithamForCreatingAndLoadingKeys)
.generatePrivate(new PKCS8EncodedKeySpec(IOUtils.toByteArray(privateKeyInputStream)));
}
我的算法定义为RSA
private String algorithamForCreatingAndLoadingKeys = "RSA";
我在下面的证书上签名:
private static X509CertImpl buildAndSignCert(X509CertInfo certInfo, PrivateKey privateKey)
throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException, IOException
{
X509CertImpl cert = new X509CertImpl(certInfo);
String algorithm = "SHA1withRSA";
// Sign the cert to identify the algorithm that's used.
cert.sign(privateKey, algorithm);
// Update the algorith, and resign.
certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM,
cert.get(X509CertImpl.SIG_ALG));
X509CertImpl newCert = new X509CertImpl(certInfo);
newCert.sign(privateKey, algorithm);
return newCert;
}
问题:如果我在没有保存和加载密钥文件的情况下创建CA证书和最终证书,我可以验证最终证书:
C: \工作区。。。。。\src\main\resources>openssl verify-CAfile ca.pem end.pem
end.pem:OK
但如果我保存并加载密钥文件并进行验证,我会得到以下错误,它清楚地表明我的最终证书没有用我的ca cert 正确签名
C: \工作区。。。。。\src\main\resources>openssl verify-CAfile ca.pemend.pem
end.pem:C=AU,L=ABC,CN=XYZ
0处的错误20深度查找:无法获取本地颁发者证书
所以,我得出的结论是,我保存私钥并加载它被窃听了。
有人能帮助我在保存和读取私钥时做错了什么吗?
非常感谢。
我上面发布的所有代码都是正确和准确的,可以创建和读取私钥文件。
我发现了加载创建的CA证书本身(而不是私钥)的问题,当我们生成X509证书时,一些问题如下:
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate loadedCaCert = (X509Certificate) f
.generateCertificate(CertificateGenerator.class.getResourceAsStream("/ca.pem"));
它从上面生成的X509Certificate中生成的序列号与我在创建CA证书时传递的序列号不同(这是另一个问题,但无论如何都没有分配给线程),并且当我们将此序列号传递给订阅者证书以识别其父CA以进行证书链接时,它失败了。
谢谢