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):
keytool -export -alias mycertalias -keystore mykeystore.jks -rfc -file mypublickey.pem
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:
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());
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):
Certificate cert = keyStore.getCertificate(alias);
BASE64Encoder encoder = new BASE64Encoder();
PublicKey publicKey = cert.getPublicKey();
System.out.println(new String(encoder.encode(publicKey.getEncoded())));
Any idea of what am I doing wrong? Thanks for the help in advance.
UPDATE:
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:
//...
Certificate cert = keyStore.getCertificate(alias);
StringWriter writer = new StringWriter();
PemWriter pemWriter = new PemWriter(writer);
pemWriter.writeObject(new PemObject("CERTIFICATE", cert.getEncoded()));
//...
Thanks!
pemWriter.writeObject(new PemObject("CERTIFICATE", publicKey.getEncoded()));this line seems iffy to me, you should convert the PublicKey to a Bouncycastle format:SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());although I think even that step is unnecessary, just writepemWriter.writeObject(publicKey.getEncoded());public void writeObject(PemObjectGenerator objGen)