iMa*_*ari 7 android rsa android-keystore android-4.3-jelly-bean
在这篇博客之后,我正在使用此代码KeyPair在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检索公钥时,会抛出NullPointerException带有消息的a chain == null.
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示例进行了比较.在该样本中生成,存储和检索密钥对的机制几乎与我实现的相同.我很困惑为什么这段代码在经过几个月的完美工作后已停止运作.
任何建议或提示将不胜感激.
显然,Android KeyStore 中的名称在所有应用程序中必须是唯一的。我有另一个应用程序,其密钥使用相同的名称。更改两个应用程序用于创建和使用密钥以在其密钥名称中包含包名称后,问题就消失了......
| 归档时间: | 
 | 
| 查看次数: | 1222 次 | 
| 最近记录: |