How to import RSA private key, which generated by openssl, into AndroidKeyStore

好久不见. 提交于 2020-01-03 09:28:21

问题


I would like to import into AndroidKeyStore a key. So, I can generate it by openssl in following way

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 into hex format, which can be converted in byteArray in android app. But it's not clear for me, How to import this byteArray into AndroidKeyStore?

So in general, my question is how import into KeyStore key which exist as a String or byteArray?

ps: I know that it is possible to generate a keyPair by keyPairGenerator.generateKeyPair(), but I would like to import my key, for example generated by openssl and then hard-coded in application.


回答1:


It's not a good idea to hard-code a private key into 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're still believe you need to do this despite this warning, read on.

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

To convert the PKCS#8 DER encoded private key into a PrivateKey:

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

To convert the PEM or DER encoded certificate into a Certificate:

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

Finally, to import the private key and the cert into Android Keystore's "myKeyAlias" entry:

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

See more advanced examples at https://developer.android.com/reference/android/security/keystore/KeyProtection.html.



来源:https://stackoverflow.com/questions/36794576/how-to-import-rsa-private-key-which-generated-by-openssl-into-androidkeystore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!