【问题标题】:Android KeyStore not saving RSA keyAndroid KeyStore 不保存 RSA 密钥
【发布时间】:2017-03-03 00:38:59
【问题描述】:

我正在使用 android keystore api 来存储 RSA 密钥对。

当我在调试模式下运行我的 android 时,它显示密钥对和证书字节已存储在密钥库中,但是当我重新加载调试器并尝试检索密钥时,密钥库似乎为空。

我希望能够通过别名检索密钥。下面的代码显示了如何创建和存储密钥对。

    public RSA(char[] password) throws Exception {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);
    Enumeration<String> aliases = ks.aliases();
    if(!aliases.hasMoreElements())
    {
        mCurrentCertificate = generateCert();
        //Store the new keypair
        FileInputStream fs = null;
        ks.load(fs, password);

        KeyStore.ProtectionParameter protParam =
                new KeyStore.PasswordProtection(password);

        java.security.cert.Certificate[] myCert =
                new java.security.cert.Certificate[] { (java.security.cert.Certificate) mCurrentCertificate};

        KeyStore.PrivateKeyEntry pkEntry =
                new KeyStore.PrivateKeyEntry(mCurrentRSAKeyPair.getPrivate(),
                        myCert);

        ks.setEntry("MyKey2", pkEntry, protParam);

        for(int i = 0; i < ks.size(); i++)
        {
            //MyKey is the previous key stored, MyKey2 is the next one
            System.out.println(ks.getCertificate("MyKey"));
        }
    }
}

【问题讨论】:

    标签: java android rsa android-keystore


    【解决方案1】:

    使用您的代码,您可以在文件系统中创建一个密钥库(它缺少 ks.store(fileOutputStream, password);,但 Android Keystore System 有一个特定的 API 来生成和使用密钥

    在这个answer 中,您有一个生成和加载 RSA 密钥的示例

    【讨论】: