Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android SecureStorage: Stop caching shared preferences instance to fix RemoveAll #20445

Merged
merged 1 commit into from
Feb 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 17 additions & 16 deletions src/Essentials/src/SecureStorage/SecureStorage.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ Task<string> PlatformGetAsync(string key)
{
try
{
ISharedPreferences sharedPreferences = GetEncryptedSharedPreferences();
if (sharedPreferences != null)
return sharedPreferences.GetString(key, null);
var prefs = GetEncryptedSharedPreferences();
if (prefs != null)
{
return prefs.GetString(key, null);
}
// TODO: Use Logger here?
System.Diagnostics.Debug.WriteLine(
Expand Down Expand Up @@ -48,53 +50,52 @@ Task PlatformSetAsync(string key, string data)
{
return Task.Run(() =>
{
using ISharedPreferencesEditor editor = GetEncryptedSharedPreferences()?.Edit();
using var prefs = GetEncryptedSharedPreferences();
using var editor = prefs?.Edit();
if (data is null)
{
editor?.Remove(key);
}
else
{
editor?.PutString(key, data);
}
editor?.Apply();
});
}

bool PlatformRemove(string key)
{
using ISharedPreferencesEditor editor = GetEncryptedSharedPreferences()?.Edit();
using var prefs = GetEncryptedSharedPreferences();
using var editor = prefs?.Edit();
editor?.Remove(key)?.Apply();
return true;
}

void PlatformRemoveAll()
{
using var editor = PreferencesImplementation.GetSharedPreferences(Alias).Edit();
using var prefs = GetEncryptedSharedPreferences();
using var editor = prefs?.Edit();
editor?.Clear()?.Apply();
}

ISharedPreferences _prefs;
ISharedPreferences GetEncryptedSharedPreferences()
{
if (_prefs is not null)
{
return _prefs;
}

try
{
var context = Application.Context;

MasterKey prefsMainKey = new MasterKey.Builder(context, Alias)
var prefsMainKey = new MasterKey.Builder(context, Alias)
.SetKeyScheme(MasterKey.KeyScheme.Aes256Gcm)
.Build();

var sharedPreferences = EncryptedSharedPreferences.Create(
return EncryptedSharedPreferences.Create(
context,
Alias,
prefsMainKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.Aes256Siv,
EncryptedSharedPreferences.PrefValueEncryptionScheme.Aes256Gcm);

return _prefs = sharedPreferences;
}
catch (InvalidProtocolBufferException)
{
Expand Down