5

So, NSUserDefaults is quite easy to use. But apparently, it is not too secure - there is no encryption. And of course the client wants the app prefs to be secure because it contains sensitive data.

But the Keychain is secure, though hard to code (apparently). So is there a way to easily convert NSUserDefaults code to Keychain code? In other words, I want to store app prefs within the Keychain. Or am I barking up the wrong tree?

cannyboy
  • 24,180
  • 40
  • 146
  • 252

3 Answers3

3

Both of the below solutions are wrappers around KeyChain API. By using them in a NSUserDefaults category, you can have clean way to access and store passwords.

For Mac OS X

You can try the EMKeyChain library that wraps the keychain in a friendly manner. If you need to store passwords, it is as simple as NSUserDefaults.

For iPhone

There is a simple wrapper: Simple iPhone Keychain Code.

Community
  • 1
  • 1
Laurent Etiemble
  • 27,111
  • 5
  • 56
  • 81
  • I think the Keychain on iPhone is a bit different than on OS X, so I'm not sure it would work. Have you used it successfully? – cannyboy May 19 '10 at 21:46
  • You are right; some functions are not exposed. I have update the answer to point to a working keychain wrapper for iPhone. – Laurent Etiemble May 20 '10 at 06:54
  • Thanks - do you know if the SciFi code can be used to store items which are not just usernames and passwords? – cannyboy May 20 '10 at 12:51
  • Don't know about the SciFi code, but the Apple API allows storage of certificates, keys, etc; so it shouldn't be that hard to extend. – Laurent Etiemble May 25 '10 at 10:10
1

For iOS (and possibly OS X) you can use my GSKeychain library. Sample 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"];

Hope this helps!

Simon Whitaker
  • 20,506
  • 4
  • 62
  • 79
0

It's extremely simple to do that using the PDKeychainBindings library. Here is an article i wrote about it recently. Sample code

Instead of this

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[[Model sharedModel] currentUser] setAuthToken:[defaults objectForKey:@"authToken"]];

Use this

PDKeychainBindings *bindings = [PDKeychainBindings sharedKeychainBindings];
[[[Model sharedModel] currentUser] setAuthToken:[bindings objectForKey:@"authToken"]];