Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save and Retrieve KeyPair in AndroidKeystore

I need to generate a RSA 2048 Keypair, then save it, and recover it if it exists.

At this moment, I have this:

SecureRandom random = new SecureRandom();
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
generator.initialize(spec, random);
return generator.generateKeyPair();

This works perfect, but now I tried to save and take it from Android Keystore, but I'm not achieving it. I tryed:

String alias = "TESTINGKEY";
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
if (!keyStore.containsAlias(alias)) {
    SecureRandom random = new SecureRandom();
    RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4);
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
    generator.initialize(spec, random);
    return generator.generateKeyPair();
} else {
    Key key = keyStore.getKey(alias, null);
    if (key instanceof PrivateKey) {
        Certificate cert = keyStore.getCertificate(alias);
        return new KeyPair(cert.getPublicKey(), (PrivateKey) key);
    } else {
        return null;
    }
}

But is not working right, because at the second run of the app, the keystore don't contains the Keypair.

In https://developer.android.com/training/articles/keystore.html?hl=es I saw that the KeyGenParameterSpec, the builder have a "alias" value, but int the RSAKeyGenParameterSpec don't.

How can I save it?

like image 273
Shudy Avatar asked Feb 08 '17 10:02

Shudy


1 Answers

With AndroidKeyStore is needed to use KeyGenParameterSpec.Builder to generate the keys. Also use AndroidKeyStore instead of SC. You can use the following code

Generate the keys (Android>=23)

KeyPairGenerator kpg = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");

kpg.initialize(new KeyGenParameterSpec.Builder(
                alias,
                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                .setKeySize(keySize)
                .build());

KeyPair keyPair = kpg.generateKeyPair();

Load the keys

KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyStore.Entry entry = keyStore.getEntry(alias, null);
PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
PublicKey publicKey = keyStore.getCertificate(alias).getPublicKey();
like image 85
pedrofb Avatar answered Oct 29 '22 21:10

pedrofb