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?