iOS: Store passwords in the keychain using MonoTouch / Xamarin.iOS

I have just updated this post a bit. Storing a password now supports data encryption. This means you can specify when the stored password is accessible (e.g. only if the device is unlocked).

After searching the web a lot I could not find a resource providing examples on how to store a password securely on an iOS device. StackOverflow.com pointed me to the iOS’s KeyChain and I found this example which does the magic using ObjectiveC:https://github.com/ldandersen/scifihifi-iphone/

As I want to give the community something back I offer a MonoTouch implementation inspired by to code referenced above for download here.

My code contains three static methods:

/// <summary>
/// Deletes a username/password record.
/// </summary>
/// <param name="sUsername">the username to query. May not be NULL.</param>
/// <param name="sService">the service description to query. May not be NULL.</param>
/// <returns>SecStatusCode.Success if everything went fine, otherwise some other status</returns>
public static SecStatusCode DeletePasswordForUsername ( string sUsername, string sService )
/// <summary>
/// Sets a password for a specific username.
/// </summary>
/// <param name="sUsername">the username to add the password for. May not be NULL.</param>
/// <param name="sPassword">the password to associate with the record. May not be NULL.</param>
/// <param name="sService">the service description to use. May not be NULL.</param>
/// <param name="eSecAccessible">defines how the keychain record is protected</param>
/// <returns>SecStatusCode.Success if everything went fine, otherwise some other status</returns>
public static SecStatusCode SetPasswordForUsername ( string sUsername, string sPassword, string sService, SecAccessible eSecAccessible )

/// <summary>
/// Gets a password for a specific username.
/// </summary>
/// <param name="sUsername">the username to query. May not be NULL.</param>
/// <param name="sService">the service description to use. May not be NULL.</param>
/// <returns>
/// The password or NULL if no matching record was found.
/// </returns>
public static string GetPasswordForUsername ( string sUsername, string sService )

You can find the demo project on Github: https://github.com/Krumelur/iOSPasswordStorage