###Important Classes
- KeyStore as the name suggests it retrives key from storage.
- KeyGenerator generate unique key through
KeyGenParameterSpec.Builder
- Cipher an alogorithm to encrypt and decrypt key from the KeyGenerator
###Usage Initialize related objects. KeyStore and KeyGenerator will be used together. Create a cipher object and specific encryption algorithm. ####1. Initialization
KeyStore mKeyStore = KeyStore.getInstance("AndroidKeyStore");
KeyGenerator mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
private final String KEY_CIPHER_ALGORITHM_MODE = String.format("%s/%s/%s", KeyProperties.KEY_ALGORITHM_AES, KeyProperties.BLOCK_MODE_CBC, KeyProperties.ENCRYPTION_PADDING_PKCS7);
Cipher mCipher = Cipher.getInstance(KEY_CIPHER_ALGORITHM_MODE);
####2. Generate Key Load KeyStore and generate key with a specific spec through KeyGenParameterSpec.Builder. Since fingerprint is available only on api 24+ so we check it with the builder.
//load first param with no specific parameter.
mKeyStore.load(null)
//generate key with specific spec through KeyGenParameterSpec.Builder
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
"default_key",
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
// Require the user to authenticate with a fingerprint to authorize every use
// of the key
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
// This is a workaround to avoid crashes on devices whose API level is < 24
// because KeyGenParameterSpec.Builder#setInvalidatedByBiometricEnrollment is only
// visible on API level +24.
// Ideally there should be a compat library for KeyGenParameterSpec.Builder but
// which isn't available yet.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.setInvalidatedByBiometricEnrollment(true);
}
mKeyGenerator.init(builder.build());
mKeyGenerator.generateKey();
####3. Encryption
Use mKeyStore to get a SecretKey
and encrypt the keyusing mCipher
mKeyStore.load(null);
SecretKey key = (SecretKey) mKeyStore.getKey("default_key", null);
mCipher.init(Cipher.ENCRYPT_MODE, key);
####4.