我的本地存储(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文件,然后将其存储在密钥库中。

最佳答案

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

10-07 12:01