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

问题描述:

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

I have PEM format file, How can verify the signature in Java, as I followed http://download.oracle.com/javase/tutorial/security/apisign/versig.html but found that Java doesnt support PEM

您可以使用 BouncyCastle 的PEM文件读取证书。 code> PEMReader 。如果内容是X.509证书,您应该获得 X509Certificate 的实例,并根据您的需要对其进行验证。

You can read a certificate in a PEM file using BouncyCastle's PEMReader. If the content is an X.509 certificate, you should get an instance of X509Certificate and verify it as you want from there.

EDIT :代码应该是(未尝试):

EDIT: Here is what the code should look like (not tried):

// 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
}

,你需要用try / finally关闭阅读器。)

(Of course, as with any I/O operations, you'll need to close the reader perhaps with try/finally.)

注意 checkValidity verify 不返回任何东西:如果它们失败,他们会抛出异常。

Note that checkValidity and verify don't return anything: instead, they throw exceptions if when they fail.