【问题标题】:Android 4.3 KeyStore - chain == null while trying to retrieve keysAndroid 4.3 KeyStore - 尝试检索密钥时链 == null
【发布时间】:2014-07-21 13:26:24
【问题描述】:

按照this blog,我正在使用此代码在Android KeyStore 中创建和存储KeyPair

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 检索公钥时,会抛出带有消息 chain == nullNullPointerException

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

获取私钥的代码也是如此。

更新:

我将我的代码与Google BasicAndroidKeyStore sample 进行了比较。该示例中生成、存储和检索密钥对的机制与我实现的机制几乎相同。我很困惑为什么这段代码在完美运行几个月后就停止运行了。

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

【问题讨论】:

    标签: android rsa android-4.3-jelly-bean android-keystore


    【解决方案1】:

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

    【讨论】:

    • 只是为了澄清——问题是在检索密钥时发生的,而不是在生成它时发生的。因此,当您尝试从不同的应用程序检索密钥时,链 == null 发生了?
    • 我知道这是一篇旧帖子,但您有没有任何参考资料表明别名在所有应用程序中应该是唯一的?
    【解决方案2】:

    就我而言,我几乎同时多次调用来获取 KeyStore。我必须创建一个实例并在它存在时引用它,否则KeyStore.getInstance("AndroidKeyStore") 返回null 并引发异常。 为了防止多个异步请求导致崩溃,请使用来自一个 KeyStore.getInstance() 的存储实例。

    【讨论】:

    • 我只在 Android 5 上遇到过这个问题。我看到了这个答案并想……不,肯定不是。所以我尝试了所有其他答案,但无济于事,绝望地回到了这个答案。你知道吗,它工作得很好!我猜这个问题已经在较新的 Android 版本中得到解决。不要小看这一点!
    【解决方案3】:

    就我而言,我试图在生成公钥之前获取它。 (getRSAPublicKey()generateKeyPair() 之前调用)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多