The Goo Software Blog

All The Goo That's Fit To Print

GSKeychain

Spurred on by reading Peeking Inside App Bundles by Nick Arnott, I went ahead and wrote a simple keychain wrapper class for iOS. GSKeychain makes storing secrets like passwords and access tokens in the keychain as easy as storing them in NSUserDefaults. Here’s a synopsis of its usage:

// Store a secret
[[GSKeychain systemKeychain] setSecret:@"t0ps3kr1t" forKey:@"myAccessToken"];

// Fetch a secret
NSString * secret = [[GSKeychain systemKeychain] secretForKey:@"myAccessToken"];

// Delete a secret
NSString * secret = [[GSKeychain systemKeychain] removeSecretForKey:@"myAccessToken"];

Currently this class should be considered a work-in-progress. Feel free to use it, but please enhance and tweak as you see fit and send me pull requests.

How about OS X?

In theory this class will work fine with OS X. The functions it uses all exist in OS X as well as iOS. However, there are some caveats:

  1. I’ve never used this class on OS X. If you try it you’ll be my guinea pig! (Please let me know how you get on.)
  2. On iOS, keychain entries are specific to an app and can’t generally be read by other apps (unless you’ve used keychain-access-groups). That doesn’t apply on OS X, so you may want to add additional data to the lookup dictionary that GSKeychain uses. (See genericLookupDictionaryForIdentifier: in GSKeychain.m to see where that lookup dictionary is created.) I’ve never used Keychain Services in OS X though, so I’m not best places to advise on this point. Read the docs.
  3. OS X has some utility functions (e.g. SecKeychainAddGenericPassword) that make interacting with the keychain a little easier and more task-centric, so you may want to use those instead.