Save and retrieve keypair in Android keystore
•
Android
I need to generate an RSA 2018 key pair, then save and restore it (if any)
At this moment, I have:
SecureRandom random = new SecureRandom();
RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4);
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
generator.initialize(spec, random);
return generator.generateKeyPair();
The effect is very good, but now I try to save and get it from Android keystore, but I don't realize it. I've tried:
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;
}
}
However, it does not work properly because the keystore does not contain key pairs in the second run of the application
stay https://developer.android.com/training/articles/keystore.html?hl=es In, I saw keygenparameterspec, which has an alias value, but int rsakeygenparameterspec does not
How do I save it?
resolvent:
Using androidkeystore requires keygenparameterspec.builder to generate keys. Also use androidkeystore instead of SC. you can use the following code
Generate key (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 key
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();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码