为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

jeck猫 2023-07-19 16:48:35
我的本地存储中有 .p7b 文件(C:\Users\Certs\cert.p7b)。 我尝试了以下方法。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 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

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

    }

}


查看完整回答
反对 回复 2023-07-19
?
慕后森

TA贡献1802条经验 获得超5个赞

您关闭了输入流。之后您将无法读取它。


您不应该使用 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();

}

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


将来,请发布您的实际代码。如果我们看不到它们,就很难知道哪些线路引起了问题。


查看完整回答
反对 回复 2023-07-19
  • 2 回答
  • 0 关注
  • 102 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信