Xamarin.Essentials: Secure Storage

Pre-release NuGet

The SecureStorage class helps securely store simple key/value pairs.

Getting Started

To access the SecureStorage functionality, the following platform-specific setup is required:

No additional setup required.

Using Secure Storage

Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

To save a value for a given key in secure storage:

try
{
  await SecureStorage.SetAsync("oauth_token", "secret-oauth-token-value");
}
catch (Exception ex)
{
  // Possible that device doesn't support secure storage on device.
}

To retrieve a value from secure storage:

try
{
  var oauthToken = await SecureStorage.GetAsync("oauth_token");
}
catch (Exception ex)
{
  // Possible that device doesn't support secure storage on device.
}

Note

If there is no value associated with the requested key, GetAsync will return null.

To remove a specific key, call:

SecureStorage.Remove("oauth_token");

To remove all keys, call:

SecureStorage.RemoveAll();

Platform Implementation Specifics

The Android KeyStore is used to store the cipher key used to encrypt the value before it is saved into a Shared Preferences with a filename of [YOUR-APP-PACKAGE-ID].xamarinessentials. The key used in the shared preferences file is a MD5 Hash of the key passed into the SecureStorage APIs.

API Level 23 and Higher

On newer API levels, an AES key is obtained from the Android KeyStore and used with an AES/GCM/NoPadding cipher to encrypt the value before it is stored in the shared preferences file.

API Level 22 and Lower

On older API levels, the Android KeyStore only supports storing RSA keys, which is used with an RSA/ECB/PKCS1Padding cipher to encrypt an AES key (randomly generated at runtime) and stored in the shared preferences file under the key SecureStorageKey, if one has not already been generated.

SecureStorage uses the Preferences API and follows the same data persistence outlined in the Preferences documentation. If a device upgrades from API level 22 or lower to API level 23 and higher, this type of encryption will continue to be used unless the app is uninstalled or RemoveAll is called.

Limitations

This API is intended to store small amounts of text. Performance may be slow if you try to use it to store large amounts of text.

API