Home » Android » java – How to use private keys from Android storage

java – How to use private keys from Android storage

Posted by: admin June 15, 2020 Leave a comment


I’m trying to import a private key from Android system storage using next code:

PrivateKey privateKey = KeyChain.getPrivateKey(activity, alias);

where alias is retrieved using KeyChain.choosePrivateKeyAlias() method. KeyChain.getPrivateKey doesn’t return null but PrivateKey object contains wrong key (all its significant fields are null). I thought that the key is not exportable and tried to use it in the next code:

Cipher rsa;
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] enc = rsa.doFinal(str.getBytes());

but got NullPointerException that comes from BouncyCastle internals.

The certificate with the key were imported from a PFX file using Android standard load from memory card function.

What I’m doing wrong?

UPD: I’ve tried to do the same with different RSA certificates and result is the same 🙁

How to&Answers:

Try the following code that is working for me perfectly:

KeyStore ks;
ks = KeyStore.getInstance("AndroidCAStore");
ks.load(null, null);
keyChain = KeyChain.getCertificateChain(ctx, certificateAlias);
privateKey = KeyChain.getPrivateKey(ctx, certificateAlias);