本文介绍了Android KeyStore-如何保存RSA私钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Web服务(由我自己制作)接收以基数64字符串编码的RSA私钥PKCS#8.我的Android应用程序必须将此密钥安全地保存到手机中.

I receive from a web service(made by myself) an RSA PrivateKey PKCS#8 encoded in a base 64 String.My Android app must save this key somewhere into the phone securely.

从Android的4.3版本开始,可以使用新的KeyStore API保存密钥.我发现了一个带有代码示例的文章该图显示了如何使用存储密钥所需的规范生成密钥对.并在以后恢复密钥.

From the 4.3 version of Android, it's possible saving keys using the new KeyStore API.I've found an article with code axample that shows how to generate a KeyPair with the Specification needed to store the keys. And after to recover the keys.

// generate a key pair
Context ctx = getContext();
Calendar notBefore = Calendar.getInstance()
Calendar notAfter = Calendar.getInstance();
notAfter.add(1, Calendar.YEAR);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx)
            .setAlias("key1")
            .setSubject(
                    new X500Principal(String.format("CN=%s, OU=%s", alais,
                            ctx.getPackageName())))
            .setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime())
            .setEndDate(notAfter.getTime()).build();

KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
kpGenerator.initialize(spec);
KeyPair kp = kpGenerator.generateKeyPair();

// in another part of the app, access the keys
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry("key1", null);
RSAPublicKey pubKey = (RSAPublicKey)keyEntry.getCertificate().getPublicKey();
RSAPrivateKey privKey = (RSAPrivateKey) keyEntry.getPrivateKey();

但是我不知道如何保存现有密钥.有谁能够帮我?预先感谢

But i don't understand how can i save an existing key to it. Can anybody help me?Thanks in advance

推荐答案

KeyStore中,私钥必须与证书(甚至是伪造的自签名证书)一起存储.要将密钥存储在AndroidKeyStore中,您应该按照以下步骤操作:

In KeyStore the private keys must be stored along with a certificate (even a fake self-signed certificate). To store your key in the AndroidKeyStore you should follow these steps:

  1. 解码Base64 PKCS#8以获得PrivateKey实例
  2. Web服务将证书(或证书链)与私钥一起发送,或者PKCS#8 Blob也包含公钥.
  3. 如果需要,您需要为私钥生成证书. BouncyCastle 库可以做到这一点(可以在).
  1. decode the Base64 PKCS#8 to get a PrivateKey instance
  2. either the web service sends a certificate (or certificate chain) along with the private key or the PKCS#8 blob also contain the public key.
  3. if required you need to generate a certificate for the private key. The BouncyCastle library can do this (a code sample can be found here).

现在您可以将密钥添加到密钥库中.

Now you can add your key to the keystore.

PrivateKey myKey = getKey();
X509Certificate certificate = getCertificate();
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
keystore.setKeyEntry("anAlias", myKey, null, new Certificate[] { certificate });

这篇关于Android KeyStore-如何保存RSA私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 23:52