Using Keychain to Store Username and Password

The keychain services on iOS provide a means to securely store content such as passwords, keys, certificates, etc. Each iOS application has a separate set of keychain items. Beginning with iOS 3.0, it is possible to share keychain items across applications.

In this tip, I will demonstrate a starting point for working with the keychain by storing and retrieving a username and password.

Keychain Demo Application

Before going any further, let me show you the sample application I wrote to test keychain access. The screenshot on the left shows two fields, one each for username and passord, along with a button to initiate the process for writing to the keychain. The figure on the right shows the fields populated upon application startup by retrieving the username and password from the keychain.

Keychain Wrapper

Apple has written an Objective-C wrapper that you can use to simplify working with the keychain, the files in the wrapper are KeychainItemWrapper.h and KeychainItemWrapper.m, both are included in the attached Xcode project.

To use the wrapper, allocate a new KeychainItemWrapper object as shown below:

I’ve specified a unique identifier (“TestAppLoginData”) for the username and password pair that I want to store in the keychain. The accessGroup is set to nil as only one application will access the keychain items in this application.

Writing to the Keychain

Once the button is pressed to save the username and password, writing to the keychain is quite straight-forward. For the username, I set an object (the username text) with the key kSecAttrAccount. I follow this by setting another object, this time the password text, with the key kSecValueData.

For this simple application, at this point we are done, that’s all that is required to write and read items with the keychain.

Notes:

Writing and retrieving values from the keychain doesn’t seem to work in the simulator.

Uninstalling an application will not remove the items from the keychain. If you run the demo application on your device, and uninstall the app, the username and password will remain in the keychain (a firmware reset will, of course, remove the keychain values).

I want to store my Encryption/Decryption Key in iOS keychain. How to implement this?
Which attribute i have to use? kSecAttrGeneric or kSecAttrAccount ???
It would be helpful if u provide sample code….
Thanks.

It is working fine in both the developer environment and production(Ad-Hoc) environment but when I upload the app on the app store and then download the app from the store, it is not saving the data into the keychain..

Dharmit, John:
I am experiencing the same.
App on Simulator, the values persist. They are there even if I remove the app.
App on iPad, using Enterprise License, they are not saved. If I remove app or terminate the app, the values are not there when I return to the app.
Anyone else experiencing this?