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

时间:2015-08-12 17:23:23

标签: java base64 pkcs#12

我正在使用需要PKCS12 Base64证书(String)的web服务,我有一个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)

1 个答案:

答案 0 :(得分:2)

pfx文件不是证书,而是密钥库。要将其转换为pem证书而不诉诸openssl,您可以执行以下操作:

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());