Android 開發 | 加密版的 SharedPreference - EncryptedSharedPreferences
介紹 根據官方文件, EncryptedSharedPreferences 使用 2-part system 來管理金鑰,並用金鑰加解密儲存的資料。 一組 Keyset(密鑰集合)包含一個或多個 Key(密鑰),用來加密解密資料。這組 Keyset 會儲存在 SharedPreferences 裡。 一把 Primary Key (主鑰) 負責加密所有的 Keysets,這把是存在 Android 的 KeyStore 裡面。 運作流程 graph TD; A[應用程式存取 EncryptedSharedPreferences] --> B{檢查 MasterKey 是否存在於 KeyStore} B -- 存在 --> C[讀取 MasterKey] B -- 不存在 --> D[建立新的 MasterKey] C --> E{檢查 KeySet 是否存在於 SharedPreferences} D --> E E -- 存在 --> F[讀取 KeySet] E -- 不存在 --> G[產生新的 KeySet 並加密存入 SharedPreferences] F --> H[使用 KeySet 加密 Key & Value] G --> H H --> I[存入 shared_prefs/*.xml 已加密的數據] 資源引用 1 2 3 4 5 6 7 8 9 10 11 // Encrypted SharedPreference implementation "androidx.security:security-crypto:1.0.0" // For Identity Credential APIs implementation "androidx.security:security-identity-credential:1.0.0-alpha03" // For App Authentication APIs implementation "androidx.security:security-app-authenticator:1.0.0-alpha02" // For App Authentication API testing androidTestImplementation "androidx.security:security-app-authenticator:1.0.0-alpha02" 這個套件基本上也可以對檔案加密,但本篇以實作 SharedPerefrences 為主,詳情可以參考 Work with data more securely。 ...