I need to store some private user's values in SharedPreferences.
I came across this article: https://medium.com/@ericfu/securely-storing-secrets-in-an-android-application-501f030ae5a3
It explains most of the things you have to do, but it seems to be missing the part about how to save the private and public key (for API<23) into the keystore.
So if we have API version 18-22 we do the following: we open a keystore
KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);
we generate the key pair
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 30);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext)
.setAlias(KEY_ALIAS)
.setSubject(new X500Principal("CN=" + KEY_ALIAS))
.setSerialNumber(BigInteger.TEN)
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.build();
KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
kpg.initialize(spec);
mEncryptionPair = kpg.generateKeyPair();
Now we can use public key for encrypting data and private key to decrypt it. But we need to save the keypair to the keystore and later retrieve it. How do I do this exactly?
I am also concerned about why Android Studio displays a warning for this line
KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
the warning:
Field requires API level 23 (current min is 14): android.security.keystore.KeyProperties#KEY_ALGORITHM_RSA
I know, this question is too old, but i had the same problem. Here is the solution if someone needs
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
spec = new KeyPairGeneratorSpec.Builder(mContext)
.setAlias(alias)
.setSubject(new X500Principal("CN=" + alias))
.setSerialNumber(BigInteger.valueOf(1337))
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.build();
} else {
spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
.setCertificateSubject(new X500Principal("CN=" + alias))
.setDigests(KeyProperties.DIGEST_SHA256)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.setCertificateSerialNumber(BigInteger.valueOf(1337))
.setCertificateNotBefore(start.getTime())
.setCertificateNotAfter(end.getTime())
.build();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With