Skip to content

Instantly share code, notes, and snippets.

@oofnivek
Last active January 11, 2024 17:31
Show Gist options
  • Save oofnivek/adaa9dd4c4ae1367eb59384b9fa45425 to your computer and use it in GitHub Desktop.
Save oofnivek/adaa9dd4c4ae1367eb59384b9fa45425 to your computer and use it in GitHub Desktop.
Extract certificate from JKS in PEM format
package org.example;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.util.io.pem.PemObject;
import java.io.*;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Security;
import java.security.cert.Certificate;
public class Main {
public static final String jksPassword = "password";
public static final String jksPath = "/Users/oofnivek/Desktop/keystore.jks";
public static final String entryAlias = "example.org";
public static void main(String[] args) {
Security.addProvider(new BouncyCastleProvider());
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance("JKS");
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
try (FileInputStream fileInputStream = new FileInputStream(jksPath)) {
keyStore.load(fileInputStream, jksPassword.toCharArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
Key key = null;
try {
key = keyStore.getKey(entryAlias, jksPassword.toCharArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
// extracting private key
try (JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(new FileWriter("private_key.pem"))) {
jcaPEMWriter.writeObject(new PemObject("PRIVATE KEY", key.getEncoded()));
System.out.println("Private key successfully extracted");
} catch (IOException e) {
throw new RuntimeException(e);
}
Certificate certificate = null;
try {
certificate = keyStore.getCertificate(entryAlias);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
// extracting certificate
try(JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(new FileWriter("certificate.pem"))){
jcaPEMWriter.writeObject(certificate);
System.out.println("Certificate successfully extracted");
} catch (IOException e) {
throw new RuntimeException(e);
}
// extract public key
try(JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(new FileWriter("public_key.pem"))){
jcaPEMWriter.writeObject(new PemObject("PUBLIC KEY", certificate.getPublicKey().getEncoded()));
System.out.println("Public key successfully extracted");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment