我希望实现与openssl命令相同的功能,但是在Java中以编程方式实现:
openssl pkcs7 -in toBeExported.p7c -inform DER -out certificate.pem -print_certs
这意味着我有DER格式的公钥证书(PKCS#7证书),我想将其中包含的原始证书解压缩到Base64文件。有没有办法做到这一点?
答案 0 :(得分:4)
像
这样的东西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编码证书。
干杯,
答案 1 :(得分:0)
让我使用现代语言功能添加一个更完整的 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());
});
}
}
}
答案 2 :(得分:-1)
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());
}
}