我正在使用以下代码在我的应用程序中存储一些加密的信息。
val masterKey = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
val sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs",
masterKey,
this,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
由于 MasterKeys 类在 Android 中已弃用,我应该使用 MasterKey 类,但我无法弄清楚获得相同定义的正确方法是什么。有人可以显示与可用的 MasterKey 和 MasterKey.Builder 类的完全匹配吗?
下面的解决方案是这样工作的:
val spec = KeyGenParameterSpec.Builder(
"_androidx_security_master_key_",
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build()
val masterKey: MasterKey = MasterKey.Builder(this)
.setKeyGenParameterSpec(spec)
.build()
val sharedPreferences = EncryptedSharedPreferences.create(
this,
"secret_shared_prefs",
masterKey, // masterKey created above
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);
最佳答案
试试这个
MasterKey masterKey = new MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
context,
SHARED_PREF_NAME,
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);
关于kotlin - 在 Android 中弃用 MasterKeys 后如何创建 masterKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62498977/