We have generate AndroidKeystore and it's working fine but randomly facing below issue.
After App reinstall its working fine.
java.security.KeyStoreException: Failed to store private key
Below is the code where we are facing the issue
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, [email protected]");
X500Name subjectName = new X500Name("CN=test, OU=test, O=test, L=test, ST=test, C=test, [email protected]");
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;
}
}
Try casting the value to key object
keyStore.setKeyEntry("Test", (Key) keyPair.getPrivate(), null, chain);
also you can use this method which has no password parameter
keyStore.setKeyEntry("Test", (Key) keyPair.getPrivate(), chain);
also try adding a value to password instead of null
String pwd = "password";
keyStore.setKeyEntry("Test", (Key) keyPair.getPrivate(), pwd, chain);
If you still fail on these two trying using encoded keys as the parameter
keyPair.getPrivate().getEncoded()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With