我正在使用EncryptedSharedPreferences来存储加密的数据。
val biometricManager = BiometricManager.from(this)
val hasFingerprint = biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS
val advanceSpec = KeyGenParameterSpec.Builder(
"master_key",
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).apply {
setBlockModes(KeyProperties.BLOCK_MODE_GCM)
setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
setKeySize(256)
if(hasFingerprint){
setUserAuthenticationRequired(true)
setUserAuthenticationValidityDurationSeconds(1)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
setInvalidatedByBiometricEnrollment(false)
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
setIsStrongBoxBacked(true)
setUserConfirmationRequired(true)
}
}
}.build()
val masterKey = MasterKeys.getOrCreate(advanceSpec)
val preferences = EncryptedSharedPreferences.create(
"TestPreferences",
masterKey,
applicationContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
实际上,我缺少BiometricPrompt部分。我认为调用setUserAuthenticationRequired(true)
将自动处理身份验证用户。但是我们必须自己展示BiometricPrompt。 isUserAuthenticationRequired
仅确保仅在授权用户后才能激活键。
val biometricPrompt = BiometricPrompt(
activity,
ContextCompat.getMainExecutor(activity),
object: BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
createSharedPreferences()
}
}
)
biometricPrompt.authenticate(promptInfo)
但是,有问题。它仅在创建EncryptedSharedPreferences
时抛出UserNotAuthenticatedException。之后,我们可以根据需要执行读取和写入操作。它没有考虑setUserAuthenticationValidityDurationSeconds(1)
。
我找到了为什么1秒后不需要身份验证的原因。这是因为,一旦启动了加密的共享首选项,它将加载用于对内存中的数据进行加密和解密的密钥,然后将这些密钥用于访问文件中的数据。您可以阅读EncryptedSharedPreference
类中的代码。这很明显。
KeysetHandle daeadKeysetHandle = new AndroidKeysetManager.Builder()
.withKeyTemplate(prefKeyEncryptionScheme.getKeyTemplate())
.withSharedPref(context, KEY_KEYSET_ALIAS, fileName)
.withMasterKeyUri(KEYSTORE_PATH_URI + masterKeyAlias)
.build().getKeysetHandle();
KeysetHandle aeadKeysetHandle = new AndroidKeysetManager.Builder()
.withKeyTemplate(prefValueEncryptionScheme.getKeyTemplate())
.withSharedPref(context, VALUE_KEYSET_ALIAS, fileName)
.withMasterKeyUri(KEYSTORE_PATH_URI + masterKeyAlias)
.build().getKeysetHandle();
DeterministicAead daead = daeadKeysetHandle.getPrimitive(DeterministicAead.class);
Aead aead = aeadKeysetHandle.getPrimitive(Aead.class);
return new EncryptedSharedPreferences(fileName, masterKeyAlias,
context.getSharedPreferences(fileName, Context.MODE_PRIVATE), aead, daead);