Import existing private key into BKS Keystore

2019-07-03 00:42发布

问题:

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

回答1:

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.