bliss
bliss

Reputation: 336

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.

Upvotes: 4

Views: 1369

Answers (1)

MLRAL
MLRAL

Reputation: 73

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).

Upvotes: 3

Related Questions