I'm trying to store a secret securely an Android application. To do so, I want to encrypt them by using a key from the Android KeyStore similar to what you would do with the KeyChain on iOS. I followed this Guide and only have to consider Android 6.0+
From my understanding, the KeyStore is a secure storage provided by Android. However, I do not really understand who unlocks access to the keystore. What I currently do is, I create a key using:
private SecretKey generateKey(String keyAlias) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
keyGenerator.init(new KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
return keyGenerator.generateKey();
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
// handling...
}
}
Now using this key fails during encryption with an android.security.KeyStoreException: Key user not authenticated
. I see that the setting setUserAuthenticationRequired(true)
requires authentication, however, I don't see how this authentication is provided. I assumed the KeyStore would be accessible whenever the user has unlocked his phone. I read about the fingerprint sensor being required to authenticate the user for the KeyStore, however, many Android devices do not have a fingerprint sensor yet.