Install AndroidKeyStore entry to AndroidCAStore

2.2k views Asked by At

I use Android application to generate KeyPair, create CSR and send it to my CA. During keyPair generation i use "AndroidKeyStore":

 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA","AndroidKeyStore");
        keyPairGenerator.initialize(new KeyGenParameterSpec.Builder(
                alias,
                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                .setKeySize(KEY_PAIR_LENGTH)
                .setDigests(KeyProperties.DIGEST_SHA256)
                .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS)
                .build());
        return keyPairGenerator.generateKeyPair();

so PrivateKey is generated and stored inside KeyStore.

When I get X509Certificate (signed CSR) from my CA i would like to install PrivateKey and Certificate using KeyChain API:

PKCS12 = ?!
Intent intent = createInstallIntent();
intent.putExtra(KeyChain.EXTRA_PKCS12, PKCS12);

Is it possible to use AndroidKeyStore in that situation? I read it is impossible to get PrivateKey from AndroidKeyStore.

1

There are 1 answers

3
Sankalp Pandya On

I too had similar requirement where in I had to retrieve the Private Key from the Keystore and I was getting the same error as yours. However, after that I tried not using KeyGenParameterSpec while storing the key in Android keystore and it worked for me. Check my code below , it might help you

Storing Key in Android Keystore :

 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
 keyPairGenerator.initialize(2048);
 KeyPair keyPair = keyPairGenerator.generateKeyPair();
 PrivateKey privateKey = keyPair.getPrivate();
 keyStore.load(null);

 X509Certificate certificate = generateCertificate(keyPair, null);
 Certificate[] certChain = new Certificate[1];
 certChain[0] = certificate;

 keyStore.setKeyEntry(Constants.KEY_ALIAS, privateKey, null, certChain);

Here X509Certificate is my self signed certificate which I am generating using X509V3CertificateGenerator.

Retrieving Private Key from Keystore :

KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.Entry entry = ks.getEntry(Constants.KEY_ALIAS, null);

if (entry == null) {
    Logger.w(getClass().getName(), "No key found under alias: " + Constants.KEY_ALIAS);
    Log.w(getClass().getName(), "Exiting signData()...");
    return null;
}

if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
    Log.w(getClass().getName(), "Not an instance of a PrivateKeyEntry");
    Log.w(getClass().getName(), "Exiting signData()...");
    return null;
}

PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();