i\'m trying to encrypt and decrypt username in app using KeyStore,
Using KeyPairGeneratorSpec to create the key in older version like 18 to 22,
KeyPairGe
the cypher transformation depends on what parameters you give to KeyGenParameterSpec
or KeyPairGeneratorSpec
.
If you want to use "RSA/ECB/PKCS1Padding"
in both cases (Android M and below) change
spec.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
to
spec.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
You can check which algorithms are available with the following piece of code:
Provider[] providers = Security.getProviders();
for (Provider p : providers) {
Log.d(TAG, "provider: " + p.getName());
Set<Provider.Service> services = p.getServices();
for (Provider.Service s : services) {
Log.d(TAG, "--> algorithm: " + s.getAlgorithm());
}
}
I avoided writing a lot of if-else by declaring an interface IKeyStoreHandler which provides all the necessary methods (add / remove keys, list all keys by their aliases, get private / public key, decrypt / encrypt text) and implementing it for both cases.