How to Secure Android Shared Preferences?

前端 未结 9 2157
我在风中等你
我在风中等你 2020-11-28 22:11

The common location where SharedPreferences are stored in Android apps is:

/data/data//shared_prefs/
         


        
9条回答
  •  感情败类
    2020-11-28 22:35

    Complete answer (api level 23+). First you need crypto from androidx.

    implementation "androidx.security:security-crypto:1.0.0-alpha02"
    

    Care : there is a significant performance difference between SharedPreferences and EncryptedSharedPreferences. You should notice that EncryptedSharedPreferences.create(...) is not so fast so you should have to store one instance at all.

    Then you have to use this to retrieve EncryptedSharedPreferences.

    public SharedPreferences getEncryptedSharedPreferences(){
       String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
       SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
           "secret_shared_prefs_file",
           masterKeyAlias,
           context,
           EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
           EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
       );
        return sharedPreferences;
    }
    

    The you just have to use preference like the "standard way". To save it :

    getEncryptedSharedPreferences().edit()
            .putString("ENCRYPTDATA", text)
            .apply()
    

    To retrieve preference value.

    getEncryptedSharedPreferences().getString("ENCRYPTDATA", "defvalue")
    

提交回复
热议问题