作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我们已经生成了 AndroidKeystore,它工作正常但随机遇到以下问题。
App重新安装后运行正常。
java.security.KeyStoreException: Failed to store private key
下面是我们遇到问题的代码
public boolean generateKeyStore() {
try {
Calendar startCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+05:30"));
Calendar endCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+05:30"));
endCal.add(Calendar.MINUTE, 15 * 24 * 60); // 15 days
Date notBefore = startCal.getTime();
Date notAfter = endCal.getTime();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
KeyPair keyPair = generator.generateKeyPair();
X500Name issuerName = new X500Name("CN=test, OU=test, O=test, L=test, ST=test, C=test, E=test@test.com");
X500Name subjectName = new X500Name("CN=test, OU=test, O=test, L=test, ST=test, C=test, E=test@test.com");
BigInteger serial = BigInteger.valueOf(Calendar.getInstance().getTimeInMillis());
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter,
subjectName, keyPair.getPublic());
ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSAEncryption")
.setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
X509Certificate cert = new JcaX509CertificateConverter().setProvider(
BouncyCastleProvider.PROVIDER_NAME).getCertificate(builder.build(signer));
Certificate[] chain = new Certificate[1];
chain[0] = cert;
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
keyStore.setKeyEntry("Test", keyPair.getPrivate(), null, chain); // --> This line raise exception
return true;
} catch (Exception e) {
Log.e("Error", "generateKeyStore", e);
return false;
}
}
最佳答案
尝试将值转换为键对象
keyStore.setKeyEntry("Test", (Key) keyPair.getPrivate(), null, chain);
你也可以使用 此方法没有密码参数
keyStore.setKeyEntry("Test", (Key) keyPair.getPrivate(), chain);
也尝试为密码添加一个值而不是 null
String pwd = "password";
keyStore.setKeyEntry("Test", (Key) keyPair.getPrivate(), pwd, chain);
如果这两个尝试使用编码 key 作为参数仍然失败
keyPair.getPrivate().getEncoded()
关于Android::java.security.KeyStoreException:无法存储私钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57592393/
我是一名优秀的程序员,十分优秀!