EncryptedSharedPreferences 的 AutoBackUp 无法恢复

TEK*_*292 3 backup android restore sharedpreferences kotlin

我用来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()
    }
}
Run Code Online (Sandbox Code Playgroud)

我目前没有实施 BackupAgent。

小智 5

根据我的理解,Jetpack Security 依赖于在设备硬件上生成的密钥,因此您不能依赖备份恢复后原始密钥仍然存在(考虑更改的设备)。

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

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

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

如果您只关心云中的备份,另一种方法 (2) 是检查加密备份(可从 Pie 上获得)。使用这种方法,您不会在本地加密共享首选项,但默认情况下会对备份进行加密。如果您需要本地加密,这种方法不适合您,但优点是,用户只需在恢复备份时输入他/她的锁屏密码,之后一切都会恢复,无需进一步的用户交互。如果您可以在没有本地加密的情况下生活,那么组合也是可以考虑的并且是更好的选择:方法 1 适用于 9 年前,方法 2 适用于 9 年后。