亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在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 從中讀?。?/p>


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 關注
  • 260 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號