2 回答

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

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();
}
始終打印或記錄捕獲的異常的完整堆棧跟蹤。畢竟,您想知道出了什么問題。隱藏它對你的程序沒有幫助,對你沒有幫助,對我們也沒有幫助。
將來,請發布您的實際代碼。如果我們看不到它們,就很難知道哪些線路引起了問題。
添加回答
舉報