下列的这个博客 http://nelenkov.blogspot.de/2013/08/credential-storage-enhancements-android-43.html,我使用此代码来创建和存储KeyPair
在 Android 密钥库中:
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
与消息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;
}
检索私钥的代码也是如此。
Update:
我将我的代码与Google BasicAndroidKeyStore 示例 http://developer.android.com/samples/BasicAndroidKeyStore/src/com.example.android.basicandroidkeystore/BasicAndroidKeyStoreFragment.html。该示例中生成、存储和检索密钥对的机制实际上与我实现的机制相同。我很困惑为什么这段代码在完美运行几个月后就停止运行了。
任何建议或提示将不胜感激。
显然,Android KeyStore 中的名称在所有应用程序中必须是唯一的。我有另一个应用程序,其密钥使用相同的名称。更改两个应用程序用于创建和使用密钥以在其密钥名称中包含包名称后,问题就消失了......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)