O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.2. Storing Values in the Keychain

Problem

You want to securely store sensitive data in the keychain.

Solution

Ensure that your app is linked against the Security framework. Then use the SecItemAdd function to add a new item to your app’s keychain.

Discussion

Keychain APIs in both iOS and OS X are C APIs. That means we don’t have an Objective-C bridge or layer on top of the C APIs, so they are a bit more difficult to use than normal APIs. The key to learning the APIs is that the requests that we send to the keychain APIs are usually packed inside dictionaries. For instance, if you want to ask the keychain services to securely store a piece of data, you put your request—including the data that you want to store, the key for that data, the identifier of your app, etc.—inside a dictionary and submit that dictionary to an API such as the SecItemAdd function. To store a piece of value in the keychain, construct a dictionary with the following keys:

kSecClass

The value of this key is usually equal to kSecClassGenericPassword for storage of secure pieces of data, such as strings.

kSecAttrService

The value of this key is usually a string. This string usually is our app bundle identifier.

kSecAttrAccount

The value of this key is a string that specifies the key to the value that we want to store. This is an arbitrary string that should make sense to you and your app.

kSecValueData

The value of this key is an instance of NSData that you want to store for a given key (kSecAttrAccount.)

The return value ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required