如何从 Java 中的 pfx 获取 PEM Base 64?

How can I get a PEM Base 64 from a pfx in Java?

我正在使用需要 PKCS12 Base64 证书(字符串)的网络服务,我有一个 pfx 文件,但我想我需要使用 base 64 转换为 PEM。

我可以用这个 bash 命令来做到这一点:

openssl base64 -in pfx.pfx -out pem.pem

但我需要在 java 中执行此操作。

我有这个方法来加载一个 *.cer 文件,然后使用 Base64.encode 来获取一个字符串,但是我得到一个异常

public X509Certificate getX509Certificate(final File certificateFile) throws CertificateException,
        IOException {
    try {
        FileInputStream is = new FileInputStream(certificateFile);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return (X509Certificate) cf.generateCertificate(is);
    } catch (FileNotFoundException e) {
        throw e;
    } catch (CertificateException e) {
        throw e;
    }

}

这是我得到的异常:

Caused by: java.security.cert.CertificateParsingException: signed fields invalid    at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1768)     at sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:196)     at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:97)     at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:339)   at fel.CFDIUtils.getX509Certificate(CFDIUtils.java:55)  at fel.CFDIUtils.getPfxBase64(CFDIUtils.java:82)    at cfdipruebas.Main.main(Main.java:33)

pfx 文件不是证书,而是密钥库。要在不借助 openssl 的情况下将其转换为 pem 证书,您可以执行以下操作:

FileInputStream fis = new FileInputStream("<path_to_pfx_file>");
java.security.KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
ks.load(fis,"pfx_password".toCharArray());
Certificate cert = ks.getCertificate("certificate_alias");

BASE64Encoder encoder = new BASE64Encoder();        
FileOutputStream fos = new FileOutputStream("<path_to_generated_pem_file>");
fos.write(X509Factory.BEGIN_CERT.getBytes());
encoder.encodeBuffer(cert.getEncoded(), fos);
fos.write(X509Factory.END_CERT.getBytes());

fos.flush();
fos.close();

如果您只想将 pfx 文件转换为 base64,就像您在问题中使用 openssl 那样,请执行以下操作:

FileInputStream fis = new FileInputStream("<path_to_pfx_file>");
ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
byte[] InBuffer = new byte[512];
int read = 0;
while ( (read = fis.read(InBuffer)) != -1 ) {
   outBuffer.write(InBuffer, 0, read);
}

BASE64Encoder encoder = new BASE64Encoder();
File fout = new File("<path_to_base64_pfx_file>");
FileOutputStream fos = new FileOutputStream(fout);

encoder.encodeBuffer(outBuffer.toByteArray(), fos);

fos.flush();
fos.close();

如果您想要一个字符串而不是将结果写入文件:

String myPfxEncodedAsBase64 = encoder.encodeBuffer(outBuffer.toByteArray());