Java – Import an existing private key into the BKS Keystore

Import an existing private key into the BKS Keystore… here is a solution to the problem.

Import an existing private key into the BKS Keystore

I have a key pair generated by openssl as follows

openssl genrsa -out private_key.pem 2048

I converted it to DER format as follows

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

Now I want to import it in

android, but I don’t want to import it because I want to protect it in keystore.

So my question is how to import an existing key into BKS keystore using keytool?

Thanks

Solution

The private key is always accompanied by the certificate chain in the keystore (including the corresponding certificate). You cannot add it to the KeyStore alone.

After generating the private key, you can

generate a self-signed certificate, which you can then use to add your private key to the KeyStore along with the certificate.

Generate a self-signed certificate

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

Create a PKCS#12 file that contains the private key and certificate

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

Finally, convert the PKCS12 KeyStore to your desired BKS storage 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 storage type JKS, you can remove the –providerclass and -providerpath parameters from the last command.

Related Problems and Solutions