Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android :: java.security.KeyStoreException: Failed to store private key

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;
    }
}
like image 401
Jigar Shekh Avatar asked Aug 21 '19 13:08

Jigar Shekh


1 Answers

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() 
like image 173
Manoj Perumarath Avatar answered Oct 17 '22 18:10

Manoj Perumarath