title: How can I get a PEM Base 64 from a pfx in Java?
body: <p>I'm using a webservice that requires a  PKCS12 Base64 certificate (a String), I have a pfx file but I suppose I need to convert to a PEM using base 64.</p>
  
  <p>I can do this with this bash command:</p>
  
  <pre><code>openssl base64 -in pfx.pfx -out pem.pem
  </code></pre>
  
  <p>But I need to do this in java.</p>
  
  <p>I have this method to load a *.cer file and then use Base64.encode to get a string , but I get an exception</p>
  
  <pre><code>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;
      }
  
  }
  </code></pre>
  
  <p>And this is the exception I get:</p>
  
  <pre><code>Caused by: java.security.cert.CertificateParsingException: signed fields invalid    at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1768)     at sun.security.x509.X509CertImpl.&lt;init&gt;(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)
  </code></pre>