title: How to export public key from pkcs12 file programmatically
body: <p>I am having trouble trying to export a public key contained in a pkcs12 file. What I am trying to achieve is the same result than with this command (but programmatically):</p>
  
  <pre><code>keytool -export -alias mycertalias -keystore mykeystore.jks -rfc -file mypublickey.pem 
  </code></pre>
  
  <p>I obtain the public key and generate a string with BouncyCastle, but the obtained result doesn't match what I obtain with the command above. Here is my code: </p>
  
  <pre><code>KeyStore keyStore = KeyStore.getInstance("pkcs12");
  keyStore.load(new FileInputStream(certPath),certPassword.toCharArray());
  String alias = "mycertalias";
  Certificate cert = keyStore.getCertificate(alias);
  
  PublicKey publicKey = cert.getPublicKey();   
  StringWriter writer = new StringWriter();
  PemWriter pemWriter = new PemWriter(writer);
  pemWriter.writeObject(new PemObject("CERTIFICATE", publicKey.getEncoded()));
  pemWriter.flush();
  pemWriter.close();
  
  System.out.println(writer.toString());
  </code></pre>
  
  <p>I have tried not using BouncyCastle and directly encoding the string, but I get the same result than before (so it doesn't match either with the result obtained with the keytool command):</p>
  
  <pre><code>Certificate cert = keyStore.getCertificate(alias);
  BASE64Encoder encoder = new BASE64Encoder();
  PublicKey publicKey = cert.getPublicKey();
  System.out.println(new String(encoder.encode(publicKey.getEncoded())));
  </code></pre>
  
  <p>Any idea of what am I doing wrong? Thanks for the help in advance.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>As suggested by @dave_thompson_085 what I actually want is to export the whole certificate in PEM format, so the valid code is like this:</p>
  
  <pre><code>//...
  Certificate cert = keyStore.getCertificate(alias);
  StringWriter writer = new StringWriter();
  PemWriter pemWriter = new PemWriter(writer);
  pemWriter.writeObject(new PemObject("CERTIFICATE", cert.getEncoded()));
  //...
  </code></pre>
  
  <p>Thanks!</p>