Tuesday, April 09, 2013

iOS - use the keychain to store your passwords

Now that we are about to write APPs that access sensitive user related data we need to find a way how to store our username and password or in our case the CAS tickets in a secure storage such as the keychain on the mac.

Fortunately Apple provides access to the local keychain on the device and furthermore they provide a sample code how this could be done, but it is not yet ARC-compatible. After some googling I found a "corrected" version on GitHub which I use now in my project.

Using this class storing something in the keychain is quite easy:
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"MyAppLogin" accessGroup:nil];
[keychainItem setObject:@"Password" forKey:(__bridge id)(kSecValueData)];
[keychainItem setObject:@"Username" forKey:(__bridge id)(kSecAttrAccount)];
and so is reading it.
NSString *password = [keychainItem objectForKey:(__bridge id)(kSecValueData)];
NSString *username = [keychainItem objectForKey:(__bridge id)(kSecAttrAccount)];
If you don't need the information stored anymore or it is expired do some cleanup
[keychainItem resetKeychainItem];
and that's all.

No comments: