问题
I would like to achieve the same what this openssl command performs, but programmatically in Java:
openssl pkcs7 -in toBeExported.p7c -inform DER -out certificate.pem -print_certs
which means that I have a public key certificate (PKCS #7 Certificate) in DER format and I want to extract the raw certificate contained there to a Base64 file. Is there a way to do this?
回答1:
Something like
FileInputStream is = new FileInputStream( "cert.pkcs7" );
CertificateFactory cf = CertificateFactory.getInstance( "X.509" );
Iterator i = cf.generateCertificates( is ).iterator();
while ( i.hasNext() )
{
Certificate c = (Certificate)i.next();
// TODO encode c as Base64...
}
should work with PKCS#7 encoded certificates.
Cheers,
回答2:
public void Read_PKCS7_Cert(String cert_file) throws FileNotFoundException,
CertificateException
{
try {
File file = new File(cert_file);
FileInputStream fis = new FileInputStream(file);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection c = cf.generateCertificates(fis);
Iterator i = c.iterator();
while (i.hasNext()) {
X509Certificate cert509 = (X509Certificate) i.next();
System.out.println("IssuerDN: " + cert509.getIssuerDN());
System.out.println("NotAfter: " + cert509.getNotAfter());
System.out.println("SerialNumber: " + cert509.getSerialNumber());
System.out.println("SigAlgName: " + cert509.getSigAlgName());
System.out.println("IssuerUniqueID: " +
Arrays.toString(cert509.getIssuerUniqueID()));
System.out.println("Signature: " + Arrays.toString(cert509.getSignature()));
System.out.println("SubjectDN: " + cert509.getSubjectDN());
}
}
catch (FileNotFoundException | CertificateException th) {
System.out.println(th.toString());
}
}
来源:https://stackoverflow.com/questions/14809754/extract-raw-certificate-from-pkcs7-file-in-java