Converting Microsoft .pvk Private Keys to Java Keystore
Developer — 16 Aug 2007 20:33 — 1639 days ago

We have some web browser extension code that is implemented both as a Java applet and as an ActiveX component (These two technologies cover both relevant cases, Java for Safari, Firefox etc, and ActiveX for MSIE6/7).

We need to sign the final binaries with a code signing certificate issued to us by a CA.

We did it the Microsoft way first (they call it Authenticode) and used their tools. These generated the key pair and we sent off the public key to the CA and got back our certificate. This certificate was in a format compatible with the tools used on the Java side (keytool) to import key material into a Java keystore. At most some minor PEM/DER conversion is required, all very easy to do using the OpenSSL command line tools:

openssl x509 -inform pem -outform der < cert.cer > cert.der

However, there are two problems getting the private key into the Java keystore:

  • The private key was stored in a proprietary Microsoft format called PVK
  • The keytool does not allow the import of private keys into a keystore, only certificates

The first problem is solved very nicely with a Windows tool written by Stephen N Henson called pvktool.exe:

pvk -in mykey.pvk -out mykey.pem

It will ask for a password used to protect the new file, choose anything you want.

The result is the private key in RSA / PEM format, which is what sane tools like OpenSSL use.

The second problem is solved by bypassing the keytool command line interface to the keystore and using a Java class called ImportKey written by Jochen Seifarth. It uses the appropriate APIs directly to store the private key.

First the key needs to be wrapped into PKCS8 / DER form:

openssl pkcs8 -topk8 -nocrypt -inform pem -outform der < mykey.pem > mykey.der

This will ask for the password you picked before. Now we are ready to run ImportKey:

java ImportKey mykey.der cert.der some_alias_goes_here

By default it creates a new keystore in your home directory called keystore.ImportKey. It also asks for a password used to protect the keystore.

To check what is in the keystore:

keytool -keystore ~/keystore.ImportKey -list
You should now be able to use signing tools like jarsigner.

Powered By blojsom