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 从中读取:
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();
}
始终打印或记录捕获的异常的完整堆栈跟踪。毕竟,您想知道出了什么问题。隐藏它对你的程序没有帮助,对你没有帮助,对我们也没有帮助。
将来,请发布您的实际代码。如果我们看不到它们,就很难知道哪些线路引起了问题。
添加回答
举报