cloudroam
2025-03-31 a7820e2f1ee06a7b43b4d351cced3343d7e1a5e2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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()
    }