Posts Under Tag: Keychain

Storing passwords in the iOS Keychain – now with iCloud sync

What’s this about?

Today, I have updated an old piece of code I wrote long ago when I started with Xamarin.iOS – back then still known as MonoTouch and I thought, why not let the world know? Maybe some folks might find the code useful.

In this article we will deal with accessing the iOS keychain and how to store and retrieve passwords.

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