package com.example.firstapp.util
|
|
import android.content.Context
|
import androidx.security.crypto.EncryptedSharedPreferences
|
import androidx.security.crypto.MasterKeys
|
import com.google.gson.Gson
|
import com.example.firstapp.model.CategoryConfig
|
|
class SecureStorage(context: Context) {
|
private val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
|
|
private val sharedPreferences = EncryptedSharedPreferences.create(
|
"secure_prefs",
|
masterKeyAlias,
|
context,
|
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
|
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
|
)
|
|
private val gson = Gson()
|
|
private fun getStorageKey(userId: String): String {
|
return "categories_$userId"
|
}
|
|
fun saveCategories(userId: String, categories: List<CategoryConfig>) {
|
val json = gson.toJson(categories)
|
sharedPreferences.edit().putString(getStorageKey(userId), json).apply()
|
}
|
|
fun getCategories(userId: String): List<CategoryConfig> {
|
val json = sharedPreferences.getString(getStorageKey(userId), null)
|
return if (json != null) {
|
gson.fromJson(json, Array<CategoryConfig>::class.java).toList()
|
} else {
|
emptyList()
|
}
|
}
|
|
// 清除指定用户的数据
|
fun clearUserData(userId: String) {
|
sharedPreferences.edit().remove(getStorageKey(userId)).apply()
|
}
|
|
// 清除所有数据
|
fun clearAllData() {
|
sharedPreferences.edit().clear().apply()
|
}
|
}
|