Android 4.3 KeyStore-尝试检索密钥时链== null [英] Android 4.3 KeyStore - chain == null while trying to retrieve keys

查看:141
本文介绍了Android 4.3 KeyStore-尝试检索密钥时链== null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此博客之后,我m使用以下代码在Android KeyStore中创建并存储 KeyPair

Following this blog, I'm using this code to create and store a KeyPair in Android KeyStore:

Context ctx = getApplicationContext();
Calendar notBefore = Calendar.getInstance();
Calendar notAfter = Calendar.getInstance();
notAfter.add(1, Calendar.YEAR);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx).
setAlias(RSA_KEYS_ALIAS).setSubject(
  new X500Principal(String.format("CN=%s, OU=%s", 
    getApplicationName(), ctx.getPackageName()))).
setSerialNumber(BigInteger.ONE).
setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime()).build();

KeyPairGenerator kpGenerator;
try {
    kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");

    kpGenerator.initialize(spec);
    kpGenerator.generateKeyPair();
} catch (Exception e) {
    showException(e);
}

当我尝试使用此代码从KeyStore检索公钥时, code> NullPointerException 与消息 chain == null 被引发。

When I try to retrieve public key from the KeyStore using this code, a NullPointerException with the message chain == null is thrown.

public RSAPublicKey getRSAPublicKey() {
    RSAPublicKey result = null;
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        KeyStore.PrivateKeyEntry keyEntry = 
            (KeyStore.PrivateKeyEntry) keyStore.getEntry(RSA_KEYS_ALIAS, null); // --< exception is thrown here
        result = (RSAPublicKey) keyEntry.getCertificate().getPublicKey();
    }
    } catch (Exception e) {
        showException(e);
    }
    return result;
}

检索私钥的代码也是如此。

The same goes with the the code to retrieve private key.

更新:

我将代码与 Google BasicAndroidKeyStore示例。该示例中生成,存储和检索密钥对的机制实际上与我实现的机制相同。我对为什么这段代码在几个月的完美工作后为何停止运行感到困惑。

I compared my code with Google BasicAndroidKeyStore sample. The mechanism to generate, store and retrieve the key pair in that sample is virtually the same to what I've implemented. I'm puzzled as to why this code has stopped functioning after a few months of perfectly working.

任何建议或提示都将不胜感激。

Any suggestions or hints would be appreciated.

推荐答案

显然,Android KeyStore中的名称在所有应用中必须唯一。我有另一个应用程序,它的密钥使用相同的名称。在更改了两个应用程序用来创建和使用密钥在其密钥名称中包含程序包名称的公共库后,问题就消失了。

Apparently names in Android KeyStore must be unique amongst all Apps. I had another app which used the same name for its keys. After changing the the common library used by both apps to create and and use keys to include package name in its key names, the problem went away...

这篇关于Android 4.3 KeyStore-尝试检索密钥时链== null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆