Search code examples
javaopensslrsaprivate-keykeytool

Is there any possibility to Exporting the private key from the PKCS12 format by using Java Keytool?


I have created keystore by using Java Keytool. Below are the steps i tried.

Preparing the certificate:

keytool -genkey -keyalg RSA -alias selfsigncert -keystore "C:\path\keystore.jks" -validity 365 -keysize 2048

Convert the JKS keystore to industry standard PKCS12 keystore

keytool -importkeystore -srckeystore C:\path\keystore.jks -destkeystore C:\path\keystore.p12 -deststoretype pkcs12

Export the client certificate

keytool -export -alias selfsigncert -keystore C:\path\keystore.p12 -rfc -file C:\path\my_self_cert.crt

Next step is to export unencrypted private key, To achieve this I could not find any command on Java keytool

I found openssl related commands only to generate private key like below

openssl pkcs12 -in identity.p12 -nodes -nocerts -out private_key.pem

Note:

  • openssl is not installed in my system ie windows 11
  • Git is not installed in my machine

Can we able to achieve this by using same Java keytool rather than go with openssl?


Solution

  • By Using java keytool i achieved my usecase.

    Creating new Keystore:

    keytool -genkey -keyalg RSA -alias dev.wso2.com -keystore "C:\dummypath\resources\security\devwso2.jks" -validity 4000
    

    Convert to pkcs12 format:

    keytool -importkeystore -srckeystore C:\dummypath\resources\security\devwso2.jks -destkeystore C:\dummypath\resources\security\devwso2.jks -deststoretype pkcs12
    

    Export public certificate:

    keytool -exportcert -alias dev.wso2.com -rfc -file "C:\dummypath\resources\security\devwso2.pem" -keystore "C:\dummypath\resources\security\devwso2.jks"
    

    import certificate into trust store

    keytool -import -alias dev.wso2.com -file "C:\dummypath\resources\security\devwso2.pem" -keystore "C:\dummypath\resources\security\client-truststore.jks"