要使用EncryptedSharedPreferences而不是MasterKeys.getOrCreate(),可以按照以下步骤操作:
implementation 'androidx.security:security-crypto:1.0.0'
val secretKeyGen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES)
secretKeyGen.init(256) // 设置密钥长度
val secretKey = secretKeyGen.generateKey()
val keyBytes = secretKey.encoded
val masterKey = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) // 用于加密密钥的主密钥
val encryptedSharedPreferences = EncryptedSharedPreferences.create(
"my_encrypted_prefs",
masterKey,
applicationContext,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
val editor = encryptedSharedPreferences.edit()
editor.putString("key", "value")
editor.apply()
val value = encryptedSharedPreferences.getString("key", "")
这样就实现了不使用MasterKeys.getOrCreate()的EncryptedSharedPreferences。请注意,密钥的生成和管理是非常重要的,需要根据具体的安全需求和使用情况进行适当的处理。