如何在Java中验证PEM格式证书

时间:2011-06-14 10:47:48

标签: java certificate pem

我有PEM格式文件,如何在Java中验证签名,因为我跟着http://download.oracle.com/javase/tutorial/security/apisign/versig.html但发现Java不支持PEM

1 个答案:

答案 0 :(得分:2)

您可以使用BouncyCastlePEMReader在PEM文件中阅读证书。如果内容是X.509证书,您应该获得X509Certificate的实例并根据需要进行验证。

编辑:以下是代码应该是什么样子(未尝试过):

// The key with which you want to verify the cert.
// This is probably a CA certificate's public key.
PublicKey publicKey = ...;

PEMReader reader = new PEMReader(new FileReader("/path/to/file.pem"));
Object pemObject = reader.readObject();
if (pemObject instanceof X509Certificate) {
    X509Certificate cert = (X509Certificate)pemObject;
    cert.checkValidity(); // to check it's valid in time
    cert.verify(publicKey); // verify the sig. using the issuer's public key
}

(当然,与任何I / O操作一样,您可能需要使用try / finally关闭阅读器。)

请注意,checkValidityverify不返回任何内容:相反,如果失败则会抛出异常。