4

I have a key pair generated by openssl in the following way

openssl genrsa -out private_key.pem 2048

The I convert it to DER format as follow

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem \ -out private_key.der -nocrypt

And now I want to import it in android but I don't want import it as it I want to protect it within a keystore.

So my question is how can I import a existing key into BKS keystore using keytool?

Thanks

RdlP
  • 1,366
  • 5
  • 25
  • 45

1 Answers1

9

A Private Key is always accompanied by a Certificate Chain (that includes the corresponding Certificate) in a KeyStore. You cannot just add it to the KeyStore just by itself.

Once you have generated the Private Key, you can generate a self-signed Certificate, you can then use this certificate to add your private key along with the certificate to the KeyStore.

Generating self-signed Certificate

openssl req -new -x509 -key [PRIVATE_KEY_FILE] -out [SELF_SIGNED_CERTIFICATE_FILE] -days 3650 -subj /[YOUR_SUBJECT_DN]

Creating a PKCS#12 file containing the PrivateKey and the Certificate

openssl pkcs12 -export -inkey [PRIVATE_KEY_FILE] -in [CERTIFICATE_FILE] -out [PKCS12_FILE.p12] -name mykey

Finally, converting the PKCS12 KeyStore to your desired BKS store type

keytool -importkeystore -srckeystore [ABOVE_P12_FILE] -srcstorepass [ABOVE_P12_PASSWORD] -srcstoretype pkcs12 -destkeystore [NEW_P12_FILE.p12] -deststorepass [NEW_P12_PASSWORD] -deststoretype bks -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath [ABSOLUTE_PATH_TO__bcprov-jdk15on-152.jar]

If you need the Java default store type JKS, you can remove the -providerclass and -providerpath arguments from the last command.

always_a_rookie
  • 4,515
  • 1
  • 25
  • 46
  • Ok, I understand, but now with PKCS#12 file, how can I read the private key in java? – RdlP Apr 19 '16 at 07:00
  • 1
    You can refer to this - http://stackoverflow.com/questions/150167/how-do-i-list-export-private-keys-from-a-keystore and http://www.java2s.com/Code/Java/Security/RetrievingaKeyPairfromaKeyStore.htm – always_a_rookie Apr 19 '16 at 14:22
  • The second command might not work (I was running it in git bash), so you should do ```winpty bash``` before. See [link](https://stackoverflow.com/questions/34156938/openssl-hangs-during-pkcs12-export-with-loading-screen-into-random-state) for more info – Andrei Manolache Mar 06 '21 at 10:58