如何在Java中以编程方式读取P7B文件

时间:2019-09-10 13:38:05

标签: java x509certificate keystore p7b

我的本​​地存储(C:\ Users \ Certs \ cert.p7b)中有.p7b文件。 This解决方案不适用于我。

我尝试了以下方法。

File file = new File("C:\Users\Certs\cert.p7b");
BufferedInputStream bis = null;
try {
     byte[] buffer = new byte[(int) file.length()];
     DataInputStream in = new DataInputStream(new FileInputStream(file));
     in.readFully(buffer);
     in.close();
     CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
     X509Certificate cert = certificatefactory.getCertificate(in);
}catch (Exception e){
     System.out.println("Exception");
}

但是它不起作用。因此,如何加载此.p7b文件,然后将其存储在密钥库中。

2 个答案:

答案 0 :(得分:2)

要从PKCS#7文件中读取证书,可以使用以下代码片段:

public static final Certificate[] readCertificatesFromPKCS7(byte[] binaryPKCS7Store) throws Exception
{
    try (ByteArrayInputStream bais = new ByteArrayInputStream(binaryPKCS7Store);)
    {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection<?> c = cf.generateCertificates(bais);

        List<Certificate> certList = new ArrayList<Certificate>();

        if (c.isEmpty())
        {
            // If there are now certificates found, the p7b file is probably not in binary format.
            // It may be in base64 format.
            // The generateCertificates method only understands raw data.
        }
        else
        {

            Iterator<?> i = c.iterator();

            while (i.hasNext())
            {
                certList.add((Certificate) i.next());
            }
        }

        java.security.cert.Certificate[] certArr = new java.security.cert.Certificate[certList.size()];

        return certList.toArray(certArr);
    }
}

答案 1 :(得分:1)

您关闭了InputStream。之后,您将无法阅读。

您不应该使用DataInputStream。您不应该使用缓冲区。只需打开文件,然后让CertificateFactory并从中读取:

X509Certificate cert = null;
File file = new File("C:\\Users\\Certs\\cert.p7b");
try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
     CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
     cert = certificatefactory.generateCertificate(in);
} catch (CertificateException e) {
     e.printStackTrace();
}

始终 打印或记录捕获到的异常的完整堆栈跟踪。毕竟,您想知道出了什么问题。隐藏它不会帮助您的程序,不会帮助您,也不会帮助我们。

将来,请发布您的实际代码。如果看不到哪几行会引起问题,就很难知道。