我想实现与此 openssl 命令相同的功能,但以 Java 编程方式:
openssl pkcs7 -in toBeExported.p7c -inform DER -out certificate.pem -print_certs
这意味着我有一个 DER 格式的公钥证书(PKCS #7 证书),我想将其中包含的原始证书提取到 Base64 文件中。有没有办法做到这一点?
我想实现与此 openssl 命令相同的功能,但以 Java 编程方式:
openssl pkcs7 -in toBeExported.p7c -inform DER -out certificate.pem -print_certs
这意味着我有一个 DER 格式的公钥证书(PKCS #7 证书),我想将其中包含的原始证书提取到 Base64 文件中。有没有办法做到这一点?
就像是
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...
}
应该使用 PKCS#7 编码的证书。
干杯,
让我使用现代语言特性添加一个更完整的 Java 类:
/**
* Reads the certificate chain from a pkcs7 file.
*/
public class Cert {
public static void main(String[] args) throws Exception {
try (InputStream inputStream = new FileInputStream("testfile.txt.pkcs7")) {
final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
certificateFactory.generateCertificates(inputStream).forEach(certificate -> {
final X509Certificate x509Certificate = (X509Certificate) certificate;
System.out.printf("subjectDN: %s%n", x509Certificate.getSubjectDN().getName());
});
}
}
}
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());
}
}