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

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


jeck猫
浏览 208回答 2
2回答

德玛西亚99

要从 PKCS#7 文件中读取证书,您可以使用以下代码片段:public static final Certificate[] readCertificatesFromPKCS7(byte[] binaryPKCS7Store) throws Exception{&nbsp; &nbsp; try (ByteArrayInputStream bais = new ByteArrayInputStream(binaryPKCS7Store);)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; CertificateFactory cf = CertificateFactory.getInstance("X.509");&nbsp; &nbsp; &nbsp; &nbsp; Collection<?> c = cf.generateCertificates(bais);&nbsp; &nbsp; &nbsp; &nbsp; List<Certificate> certList = new ArrayList<Certificate>();&nbsp; &nbsp; &nbsp; &nbsp; if (c.isEmpty())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // If there are now certificates found, the p7b file is probably not in binary format.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // It may be in base64 format.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // The generateCertificates method only understands raw data.&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Iterator<?> i = c.iterator();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (i.hasNext())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; certList.add((Certificate) i.next());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; java.security.cert.Certificate[] certArr = new java.security.cert.Certificate[certList.size()];&nbsp; &nbsp; &nbsp; &nbsp; return certList.toArray(certArr);&nbsp; &nbsp; }}

慕后森

您关闭了输入流。之后您将无法读取它。您不应该使用 DataInputStream。您不应该使用缓冲区。只需打开文件并让CertificateFactory 从中读取:X509Certificate cert = null;File file = new File("C:\\Users\\Certs\\cert.p7b");try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {&nbsp; &nbsp; &nbsp;CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");&nbsp; &nbsp; &nbsp;cert = certificatefactory.generateCertificate(in);} catch (CertificateException e) {&nbsp; &nbsp; &nbsp;e.printStackTrace();}始终打印或记录捕获的异常的完整堆栈跟踪。毕竟,您想知道出了什么问题。隐藏它对你的程序没有帮助,对你没有帮助,对我们也没有帮助。将来,请发布您的实际代码。如果我们看不到它们,就很难知道哪些线路引起了问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java