Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access EncryptedSharedPreferences from other activities

First Activity

try {
    masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
    sharedPreferences = EncryptedSharedPreferences.create(
            "secret_shared_prefs",
            masterKeyAlias,
            getApplicationContext(),
            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    );
} catch (GeneralSecurityException | IOException e) {
    e.printStackTrace();
}

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("memberID", response.body().get(0).getMemberID().toString()).commit();

Second Activity

SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("secret_shared_prefs", MODE_PRIVATE);
sharedPreferences.getString("memberID", "unknown");

Within the same activity, getSharedPreferences() works as expected. When trying to access the preferences in another activity using this code, it always returns the default value. It seems there is a problem with decryption.

like image 989
bliss Avatar asked Oct 20 '25 16:10

bliss


1 Answers

Update for anyone running into this issue. I had the same problem, and fixed it by initializing the sharedPreferences the same way as in the first activity. So (in the example given above) the line in the second activity:

SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("secret_shared_prefs", MODE_PRIVATE);

is replaced by:

try {
masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
sharedPreferences = EncryptedSharedPreferences.create(
        "secret_shared_prefs",
        masterKeyAlias,
        getApplicationContext(),
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
} catch (GeneralSecurityException | IOException e) {
    e.printStackTrace();
}

and can now be accessed by the regular getString(key, deafult) method:

sharedPreferences.getString("memberID","unknown");

For newbies such as myself I would also recommend checking the .xml file where the preferences are saved to check if they are actually encrypted (can be found in data/data/"application_name"/shared_prefs/"preference_name".xml).

like image 117
MLRAL Avatar answered Oct 23 '25 05:10

MLRAL