使用加密共享首选项的自动备份无法恢复



我正在使用EncryptedSharedPreferences在本地存储用户信息(如果您不熟悉,请参阅此内容(。我已经使用备份规则实现了自动备份。我备份了首选项,清除了应用程序上的数据,并尝试还原数据(按照备份和还原概述的步骤进行操作(。

查看Android Studio中的设备文件资源管理器,我可以确认我的首选项文件正在恢复(它已正确命名并且其中有加密数据(。但是,我的应用程序的功能就像首选项文件不存在一样。

我错过了什么?

首选项代码:

class PreferenceManager(context: Context) {
companion object {
private const val KEY_STORE_ALIAS = "APP_KEY_STORE"
private const val privatePreferences = "APP_PREFERENCES"
}
// See https://developer.android.com/topic/security/data#kotlin for more info
private val sharedPreferences = EncryptedSharedPreferences.create(
privatePreferences,
KEY_STORE_ALIAS,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
init {
//val all = sharedPreferences.all
//for (item in all) {
//Log.e("PREFERENCES", "${item.key} - ${item.value}")
//}
}
@SuppressLint("ApplySharedPref")
fun clear() {
// Normally you want apply, but we need the changes to be done immediately
sharedPreferences.edit().clear().commit()
}
fun readBoolean(key: String, defaultValue: Boolean): Boolean {
return sharedPreferences.getBoolean(key, defaultValue)
}
fun readDouble(key: String): Double {
return sharedPreferences.getFloat(key, 0f).toDouble()
}
fun readString(key: String): String {
return sharedPreferences.getString(key, "")!!
}
fun removePreference(key: String) {
sharedPreferences.edit().remove(key).apply()
}
fun writeBoolean(key: String, value: Boolean) {
sharedPreferences.edit().putBoolean(key, value).apply()
}
fun writeDouble(key: String, value: Double) {
sharedPreferences.edit().putFloat(key, value.toFloat()).apply()
}
fun writeString(key: String, value: String) {
sharedPreferences.edit().putString(key, value).apply()
}
}

我目前没有实施备份代理。

据我了解,Jetpack 安全性依赖于在设备硬件上生成的密钥,因此您不能依赖备份还原后原始密钥仍然存在(考虑更改的设备(。

加密的安全性取决于密钥的安全性,只要它不能离开密钥库或设备,备份和恢复就无法自动工作(没有用户交互(。

我的方法 (1( 是您要求用户输入密码,根据该密码加密您的常规共享首选项(可能使用另一个加密库:例如 https://github.com/iamMehedi/Secured-Preference-Store(,并使用 Jetpack 中的加密共享首选项保存密码。恢复备份后,要求用户输入密码,使用Jetpack再次保存密码并解密常规共享首选项。 这样,即使硬件密钥库发生更改,您也可以恢复备份。缺点是,用户需要记住密码。

我对我的应用程序遵循这种方法,只是不是使用共享首选项(它们在我的用例中不明智(,而是在应用程序数据库中。

另一种方法 (2( 是检查加密备份(可从 Pie 开始(,如果您只关心云中的备份。使用这种方法,您不会在本地加密共享首选项,但默认情况下会加密备份。如果您需要本地加密,这种方法不适合您,但优点是,用户只需在还原备份时键入他/她的锁屏密码,然后无需进一步的用户交互即可还原所有内容。 组合也是可以想象的,并且是可取的,如果你可以在没有本地加密的情况下生活:方法 1 用于 9 后,方法 2 用于 9 后。

正如@Floj12提到的EncryptedSharedPreferences使用密钥库,您无法备份密钥库,因此当您的加密数据恢复时,您将无法解密它。 这是非常可悲的,谷歌强迫两件事不能一起工作。Android 上的密钥库没有像 iOS 上的钥匙串那样的备份选项。

在这里,我将为您提供更多选择,如何备份数据:

  • 将用户数据存储在一个后端
  • 使用用户存储的令牌解密备份
  • 为所有应用设置静态密码
  • 用户在设置中手动导出备份

我在这里写了更多: https://medium.com/@thecodeside/android-auto-backup-keystore-encryption-broken-heart-love-story-8277c8b10505

最新更新