Keychain is really a pain to use, and I didn’t want to spend the time to figure it all out, so I went looking for a framework that would do the dirty work for me. I found SFHFKeychainUtils and it has been super slick! In this tutorial, I’ll show you how to leverage SFHFKeychainUtils in order to save a username/password to keychain and also retrieve the password given the username. Just follow these simple steps:
1. Get SFHFKeychainUtils
I found it on GitHub at http://github.com/ldandersen/scifihifi-iphone/tree/master/security/ – just get the SFHFKeychainUtils.h and SFHFKeychainUtils.m files and add them to your project.
2. Import it
In the implementation file where you want to save or retrieve the password, be sure you import the SFHF Keychain Utils header file as shown below:
#import “LoginViewController.h”#import “SFHFKeychainUtils.h”@implementation LoginViewController
3. Save a Username/Password
Here you can see how simple it is to add the username/password to the iPhone’s keychain. The storeUsername:andPassword:forServiceName:updateExisting:error method will take care of all the work for us if we give it the correct parameters. I am getting the username and password from two UITextFields in the app called usernameField and passwordField, respectively. The Service Name can be anything you want, as long as you remember it as you’ll need to enter that same string value in order to retrieve the password (see step 4).
4. Retrieve the Password from Keychain
As you can see, it’s not any more difficult to retrieve the password from keychain using SFHFKeychainUtils. I specified my username “Gorgando” and the same service name we used before “myApp”. The password that corresponds to this username and service name in the keychain will be returned as an NSString.
So don’t be afraid to use the keychain! It is the most secure way to store passwords in an iPhone application. Both plists and the Settings.Bundle are very insecure ways to store passwords because the passwords are stored in plaintext, visible to anyone who accesses them. Let me know if you have any questions – good luck!