[英]java.security.KeyStore shows only one of two certs in a p12 file
好的,我通過執行以下操作在瀏覽器中導出了所有證書:工具,選項...,高級,加密,查看證書,您的證書,全部備份...(在Firefox中)。
證書列表中有4個證書,兩個在一個名稱下,具有不同的序列號,另外兩個在另一個名稱下,具有兩個其他不同的序列號。 因此,總而言之,有四個證書,其中兩個具有相同的名稱,但序列號不同。
如果將這個p12文件導入到另一台計算機上的另一個瀏覽器中,則將獲得所有四個證書(如預期)。
-但是-
當我使用java.security。*包打開p12文件並查看size()時,它在p12文件中僅顯示兩個證書。 當我遍歷別名時,我只會看到兩個證書。 KeyStore對象中是否有東西可以讓我訪問所有四個證書? 這很困難,因為兩對別名相同,只是序列號不同。 在此先感謝您提供的任何幫助。
好的,回答我自己的古老問題...我了解到Java並不擅長讀取p12文件。 它使用每個證書的別名作為密鑰創建一個哈希圖,因此,如果有兩個具有相同別名的證書,Java將用相同別名(密鑰)的第二個證書破壞第一個證書,而每個別名僅產生一個證書。
將證書導入瀏覽器時,瀏覽器將獲取p12文件中的所有條目(而不關心別名)。
解決此問題的方法是使用Java運行時exec功能調用openssl,並將每個證書的輸出通過管道傳遞到String中,然后使用該字符串創建X509Certificate。 這是一些示例代碼(我無法復制和粘貼,因為我的開發箱未連接互聯網):
private ArrayList<X509Certificate> parseCerts( String fileName, String pwd ) {
ArrayList certsFromP12File = new ArrayList();
String cmdLine = "/usr/bin/openssl pkcs12 -info -in " + fileName + " -clcerts -nokeys -passin pass:" + pwd;
String line;
Process p = Runtime.getRuntime().exec( cmdLine );
BufferedReader input = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
boolean readingCert = false;
boolean gotCertToProcess = false;
String certString;
while ((line=input.readLine()) != null ) {
if ( line.contains("-----BEGIN CERTIFICATE-----") ) {
readingCert = true;
}
if ( readingCert ) {
certString += line + System.getProperty("line.separator");
}
if ( line.contains("-----END CERTIFICATE-----") ) {
readingCert = false;
getCertToProcess = true;
}
if ( gotCertToProcess ) {
X509Certificate cert = null;
byte[] cert_bytes = certString.getBytes();
ByteArrayInputStream certInputStream = new ByteArrayInputStream(cert_bytes);
cert = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate( certInputStream );
certsFromP12File.add( cert );
gotCertToProcess = false;
certString = "";
}
}
input.close();
return certsfromP12File;
}
希望對別人有幫助。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.