Dealing with a Java keystore when keytool is not enough

It seems odd but the keytool program for handling a Java keystore is missing two rather obvious abilites.
One missing ability is that keytool is unable to import a private key and the corresponding certificate to create a Java keystore from scratch.
Another is to provide a way to extract a private key from the Java keystore.

All you need is wget, a java compiler, OpenSSL and some spare time.

ImportKey.java was written by Joachim Karrer and Jens Carlberg
ExportPriv.java was written by Alexey Zilber
Base64Coder.java was written by Christian d’Heureuse, Inventec Informatik AG, Switzerland

  1. How to create a fresh Java keystore with a private key and a corresponding certificate
        $ openssl pkcs8 -topk8 -nocrypt -outform der -in somename.key.decrypted -out somename_pkcs8_key.der
        $ openssl x509 -inform PEM -outform DER -in somename.crt -out somename_certificate.der
        $ wget http://www.agentbob.info/agentbob/80/version/default/part/AttachmentData/data/ImportKey.java
        $ javac ImportKey.java
        $ java ImportKey somename_pkcs8_key.der somename_certificate.der
    

    This will create a keystore somewhere (for me, on a Windows machine, the location was: C:\Documents and Settings\snowy\keystore.ImportKey ).

  2. How to extract a private key from the Java keystore
        $ keytool -export -alias mykey -keystore mystorage.jks -file exported-der.crt
        $ openssl x509 -out exported-pem.crt -outform pem -in exported-der.crt -inform der
        $ wget http://mark.foster.cc/pub/java/ExportPriv.java
        $ wget http://www.source-code.biz/base64coder/java/Base64Coder.java.txt 
        $ mv   Base64Coder.java.txt Base64Coder.java
        $ javac ExportPriv.java Base64Coder.java
        $ java ExportPriv mystorage.jks mykey changeit > exported-pkcs8.key
    
Advertisements

3 thoughts on “Dealing with a Java keystore when keytool is not enough

  1. I have an error here

    javac ExportPriv.java Base64Coder.java

    javac ExportPriv.java Base64Coder.java
    ExportPriv.java:38: error: cannot access Base64Coder
    char[] b64 = Base64Coder.encode(privKey.getEncoded());
    ^
    bad class file: ./Base64Coder.class
    class file contains wrong class: biz.source_code.base64Coder.Base64Coder
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    1 error

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s