在这篇博客之后,我正在使用此代码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示例进行了比较.在该样本中生成,存储和检索密钥对的机制几乎与我实现的相同.我很困惑为什么这段代码在经过几个月的完美工作后已停止运作.
任何建议或提示将不胜感激.