如何在 java 中以编程方式读取 p7b 文件

How to read a p7b file programmatically in java

我的本地存储中有 .p7b 文件 (C:\Users\Certs\cert.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 文件,然后将其存储在密钥库中。

要从 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);
    }
}

您关闭了 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();
}

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

以后请post您的实际代码。如果我们看不到它们,就很难知道是哪些线路导致了问题。