[java] Converting a Java Keystore into PEM Format

I am trying to convert from a Java keystore file into a PEM file using keytool and openssl applicactions. But I could not find a good way to do the conversion. Any ideas?

Instead of converting the keystore directly into PEM I tried to create a PKCS12 file first and then convert into relevant PEM file and Keystore. But I could not establish a connection using them. (Note that I just need a PEM file and a Keystore file to implement a secured connection. There is no restriction like "Start from a java keystore file". :) So starting from other formats is acceptable with my case)

But a direct conversion method from jks to pem is preferable.

This question is related to java encryption https openssl ssl-certificate

The answer is


Converting a Java Keystore into PEM Format

The most precise answer of all must be that this is NOT possible.

A Java keystore is merely a storage facility for cryptographic keys and certificates while PEM is a file format for X.509 certificates only.


The keytool command will not allow you to export the private key from a key store. You have to write some Java code to do this. Open the key store, get the key you need, and save it to a file in PKCS #8 format. Save the associated certificate too.

KeyStore ks = KeyStore.getInstance("jks");
/* Load the key store. */
...
char[] password = ...;
/* Save the private key. */
FileOutputStream kos = new FileOutputStream("tmpkey.der");
Key pvt = ks.getKey("your_alias", password);
kos.write(pvt.getEncoded());
kos.flush();
kos.close();
/* Save the certificate. */
FileOutputStream cos = new FileOutputStream("tmpcert.der");
Certificate pub = ks.getCertificate("your_alias");
cos.write(pub.getEncoded());
cos.flush();
cos.close();

Use OpenSSL utilities to convert these files (which are in binary format) to PEM format.

openssl pkcs8 -inform der -nocrypt < tmpkey.der > tmpkey.pem
openssl x509 -inform der < tmpcert.der > tmpcert.pem

Try Keystore Explorer http://keystore-explorer.org/

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. It does openssl/pkcs12 as well.


Direct conversion from jks to pem file using the keytool

keytool -exportcert -alias selfsigned -keypass password -keystore test-user.jks -rfc -file test-user.pem

I kept getting errors from openssl when using StoBor's command:

MAC verified OK
Error outputting keys and certificates
139940235364168:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:535:
139940235364168:error:23077074:PKCS12 routines:PKCS12_pbe_crypt:pkcs12 cipherfinal error:p12_decr.c:97:
139940235364168:error:2306A075:PKCS12 routines:PKCS12_item_decrypt_d2i:pkcs12 pbe crypt error:p12_decr.c:123:

For some reason, only this style of command would work for my JKS file

keytool -importkeystore -srckeystore foo.jks \
   -destkeystore foo.p12 \
   -srcstoretype jks \
   -srcalias mykey \
   -deststoretype pkcs12 \
   -destkeypass DUMMY123

The key was setting destkeypass, the value of the argument did not matter.


First dump the keystore from JKS to PKCS12

1. keytool -importkeystore -srckeystore ~/.android/debug.keystore -destkeystore intermediate.p12 -srcstoretype JKS -deststoretype PKCS12

Dump the new pkcs12 file into pem

  1. openssl pkcs12 -in intermediate.p12 -nodes -out intermediate.rsa.pem

You should have both the cert and private key in pem format. Split them up. Put the part between “BEGIN CERTIFICATE” and “END CERTIFICATE” into cert.x509.pem Put the part between “BEGIN RSA PRIVATE KEY” and “END RSA PRIVATE KEY” into private.rsa.pem Convert the private key into pk8 format as expected by signapk

3. openssl pkcs8 -topk8 -outform DER -in private.rsa.pem -inform PEM -out private.pk8 -nocrypt


I found a very interesting solution:

http://www.swview.org/node/191

Then, I divided the pair public/private key into two files private.key publi.pem and it works!


Well, OpenSSL should do it handily from a #12 file:

openssl pkcs12 -in pkcs-12-certificate-file -out pem-certificate-file
openssl pkcs12 -in pkcs-12-certificate-and-key-file -out pem-certificate-and-key-file

Maybe more details on what the error/failure is?


In case you don't have openssl installed and you are looking for a quick solution, there is software called portcle which is very useful and small to download.

The disadvantage is that there is no command line as far as I know. But from the GUI, it is pretty straight forward to export a PEM private key:

  1. Open you JKS key store
  2. Right click over your private key entry and select export
  3. Select Private Key and certificates and PEM format

    Export PEM private key from JKS with Portcle


Simplified instructions to converts a JKS file to PEM and KEY format (.crt & .key):

keytool -importkeystore -srckeystore <Source-Java-Key-Store-File> -destkeystore <Destination-Pkcs12-File> -srcstoretype jks -deststoretype pkcs12 -destkeypass <Destination-Key-Password>

openssl pkcs12 -in <Destination-Pkcs12-File> -out <Destination-Pem-File>

openssl x509 -outform der -in <Destination-Pem-File> -out <Destination-Crt-File>

openssl rsa -in <Destination-Pem-File> -out <Destination-Key-File>

first create keystore file as

C:\Program Files\Android\Android Studio\jre\bin>keytool -keystore androidkey.jks -genkeypair -alias androidkey

Enter keystore password:
Re-enter new password:
What is your first and last name? Unknown: FirstName LastName
What is the name of your organizational unit? Unknown: Mobile Development
What is the name of your organization? Unknown: your company name
What is the name of your City or Locality? What is the name of your State or Province?
What is the two-letter country code for this unit? Unknown: IN //press enter

Now it will ask to confirm

Is CN=FirstName LastName, OU=Mobile Development, O=your company name, L=CityName, ST=StateName, C=IN correct? [no]: yes

Enter key password for (RETURN if same as keystore password): press enter if you want same password

key has been generated, now you can simply get pem file using following command

C:\Program Files\Android\Android Studio\jre\bin>keytool -export -rfc -alias androidkey -file android_certificate.pem -keystore androidkey.jks
Enter keystore password:
Certificate stored in file


Converting a JKS KeyStore to a single PEM file can easily be accomplished using the following command:

keytool -list -rfc -keystore "myKeystore.jks" | sed -e "/-*BEGIN [A-Z]*-*/,/-*END [A-Z]-*/!d" >> "myKeystore.pem"

Explanation:

  1. keytool -list -rfc -keystore "myKeystore.jks" lists everything in the 'myKeyStore.jks' KeyStore in PEM format. However, it also prints extra information.
  2. | sed -e "/-*BEGIN [A-Z]*-*/,/-*END [A-Z]-*/!d" filters out everything we don't need. We are left with only the PEMs of everything in the KeyStore.
  3. >> "myKeystore.pem" write the PEMs to the file 'myKeyStore.pem'.

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to encryption

mcrypt is deprecated, what is the alternative? Remove 'b' character do in front of a string literal in Python 3 How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption How to decrypt Hash Password in Laravel RSA encryption and decryption in Python How to fix Invalid AES key length? gpg decryption fails with no secret key error 7-Zip command to create and extract a password-protected ZIP file on Windows? How do I encrypt and decrypt a string in python? AES Encrypt and Decrypt

Examples related to https

What's the net::ERR_HTTP2_PROTOCOL_ERROR about? Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website Android 8: Cleartext HTTP traffic not permitted ssl.SSLError: tlsv1 alert protocol version Invalid self signed SSL cert - "Subject Alternative Name Missing" How do I make a https post in Node Js without any third party module? Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint How to force Laravel Project to use HTTPS for all routes? Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback Use .htaccess to redirect HTTP to HTTPs

Examples related to openssl

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib How to install OpenSSL in windows 10? SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7 Homebrew refusing to link OpenSSL Solving sslv3 alert handshake failure when trying to use a client certificate How to install latest version of openssl Mac OS X El Capitan How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

Examples related to ssl-certificate

How to install OpenSSL in windows 10? Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] Letsencrypt add domain to existing certificate javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure bypass invalid SSL certificate in .net core How to add Certificate Authority file in CentOS 7 How to use a client certificate to authenticate and authorize in a Web API This certificate has an invalid issuer Apple Push Services iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”