Search code examples
androidkotlinxamarin.androidandroid-storage

Retrieve Xamarin secured storage data from native Kotlin Android


I have an application written in Xamarin that saves data using SecureStorage.SetAsync. Now I need to convert the application into native Kotlin and Swift projects. Xamarin stores the data in the iOS keychain which is relatively simple to retrieve. However I am struggling to retrieve the data in Kotlin Android as I believe I need to find the key and decrypt the data manually.

How do I go about retrieving the data in Android?


Solution

  • According to the official document about the Platform Implementation Specifics of the SecureStorage API, it used the android native api Shared Preferences to store the data.

    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 (not a cryptographic key, the key to the value) used in the shared preferences file is a MD5 Hash of the key passed into the SecureStorage APIs.

    So I have tried this SecureStorage.SetAsync("test", "hahaha");. Then I searched about the android default location of the shared preferences file, it is in the /data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME.xamarinessentials.xml.

    I checked the file with the Android Studio's Device File Explorer:

    enter image description here

    The value has been encrypted, you can check the source code about encrypting the string. In addition, you can check the source code about how did it use the shared preferences var sharedPreferences = GetSharedPreferences(sharedName). And the sharedName is the string Alias = $"{AppInfo.PackageName}.xamarinessentials" in the SecureStorage class.

    So I used the android native api to read the shared preferences file:

    var name = this.PackageName + ".xamarinessentials";
    var sp = GetSharedPreferences(name, FileCreationMode.Private);
    var value = sp.GetString("test",null);
    

    And the debug result:

    enter image description here

    The value is encrypted and you need to decrypt it according to the source code about encrypting the string. So you can just convert the three line c# code to kotlin code to get the value.

    In addition, if you want to convert the xamarin app to Android Kotlin app, you can use the native SharedPreferences api directly. I can't understand why you need to Retrieve Xamarin secured storage data from native Kotlin Android.