本文介绍了如何将由openssl生成的RSA私钥导入AndroidKeyStore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个密钥导入到AndroidKeyStore中.因此,我可以按以下方式通过openssl生成它

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

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

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

然后我可以将其从private2048.der转换为十六进制格式,可以在android应用中将其转换为byteArray.但是我不清楚如何将这个byteArray导入AndroidKeyStore?

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?

因此,总的来说,我的问题是如何将以String或byteArray形式存在的KeyStore密钥导入?

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

ps:我知道可以通过keyPairGenerator.generateKeyPair()生成一个keyPair,但是我想导入我的密钥,例如由openssl生成,然后在应用程序中进行硬编码.

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.

推荐答案

将私钥硬编码到应用程序中不是一个好主意. 此密钥已被盗,因为您的APK的内容不是秘密的,因此可以从APK中提取密钥.如果您仍然相信尽管有此警告,您仍然需要这样做,请继续阅读.

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.

要将私钥导入Android Keystore,您需要将其表示为PrivateKey实例,然后还需要表示为X509Certificate实例的X.509证书(用于与私钥相对应的公钥).这是因为JCA KeyStore抽象不支持在没有证书的情况下存储私钥.

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.

要将PKCS#8 DER编码的私钥转换为PrivateKey:

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

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

要将PEM或DER编码的证书转换为证书:

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

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

最后,要将私钥和证书导入Android Keystore的"myKeyAlias"条目:

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});

https://developer.android.com上查看更多高级示例. /reference/android/security/keystore/KeyProtection.html .

这篇关于如何将由openssl生成的RSA私钥导入AndroidKeyStore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:05