How to import RSA private key generated by openssl into AndroidKeyStore

I would like to import a key into AndroidKeyStore. So, I can generate it using openssl as follows

openssl rsa -text -in privateKey2048.pem

openssl pkcs8 -topk8 -inform PEM -in./privateKey2048.pem -outform DER -out private2048.der -nocrypt

then I can convert it from private2048.der to hexadecimal format, which can be converted to byteArray in android application. But it is not clear to me, How to import this byteArray into AndroidKeyStore?

So, in general, my question is how to import a KeyStore key that exists as a String or byteArray?

ps: I know that you can create keyPair using keyPairGenerator.generateKeyPair (), but I would like to import my key, for example, generated openssl and then hardcoded in the application.

+6
source share
1 answer

It is not recommended that you write the private key to your application. This key is compromised because the contents of your APK are not secret, and thus the key can be extracted from the APK. If you still believe that you need to do this despite this warning, read on.

To import the private key into Keystore Android, you need to present it as an instance of PrivateKey, and then you also need the X.509 certificate (for the public key corresponding to the private key), presented as an instance of X509Certificate. This is because the JCA KeyStore abstraction does not support storing private keys without a certificate.

To convert PKCS # 8 DER private key to PrivateKey:

PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate( new PKCS8EncodedKeySpec(privateKeyPkcs8)); 

To convert a PEM or DER certificate to a certificate:

 Certificate cert = CertificateFactory.getInstance("X.509").generateCertificate( new ByteArrayInputStream(pemOrDerEncodedCert)); 

Finally, to import the private key and certificate into the Keystore entry in Android "myKeyAlias":

 KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null); ks.setKeyEntry("myKeyAlias", privateKey, null, new Certificate[] {cert}); 

See https://developer.android.com/reference/android/security/keystore/KeyProtection.html for more detailed examples.

+4
source

All Articles