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.
What is the iOS keychain?
Think of it as a “secure” storage inside your iOS device where you can place small chunks of sensitive information, like passwords, private keys of certificates and so on. You noticed the quotes around secure? Well, the keychain is not really secure. It can be accessed pretty easy on jailbroken devices and you better not store super-sensitive data in there. Or better: encrypt your data first, then store it in the keychain.
Ok, you decided that your passwords are not the ones you use for your online banking and you want to put them into the keychain and protect them as good as iOS allows you to. Here’s how to do it using Xamarin.iOS and my little helper class:
// Store a password. KeychainHelpers.SetPasswordForUsername ( "email@example.com", "my password", "myService", SecAccessible.WhenUnlockedThisDeviceOnly, false ); // Retrieve a password KeychainHelpers.GetPasswordForUsername ("firstname.lastname@example.org", "myService", false); // Delete a password KeychainHelpers.DeletePasswordForUsername ("email@example.com", "myService", false);
Pretty straight forward. About the parameters:
- “firstname.lastname@example.org” is the username or generally the key we want to use to associate the password “my password” with.
- “myService” is the service ID we use. You will usually set this to your application name, or feature of your application, like “MyAppLoginPasswords”.
- “SecAccessible.WhenUnlockedThisDeviceOnly” specifies how secure your want your data to be stored. This specific value for instance, says that the password can only be read when the device is unlocked and it also states that the keychain entry will not be included into a backup.
- The boolean “fals” indicates that we do not want to have this keychain entry being synced via iCloud to other devices. This is a new iOS7 feature. You can set this to true to have your keychain entries magically available on your other devices.
Note that the boolean that indicates synchronization has to be specified for retrieval and deletion, too. In fact, it acts as a filter. If you use the same username and the same service identifier but different settings for synchronization, effectively two entries in the keychain will be made.
Alright, quick post. Here’s the link to the Github repo: