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.

Below are the definitions for the textfields and the button:

UITextField *username = [[UITextField alloc] initWithFrame:CGRectMake(40, 30, 240, 30)];
[username setBorderStyle:UITextBorderStyleRoundedRect];
UITextField *password = [[UITextField alloc] initWithFrame:CGRectMake(40, 75, 240, 30)];
[password setBorderStyle:UITextBorderStyleRoundedRect];
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[testButton setFrame:CGRectMake(80, 130, 160, 40)];
[testButton addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];        
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:

KeychainItemWrapper *keychain = 
 [[KeychainItemWrapper alloc] initWithIdentifier:@"TestAppLoginData" accessGroup:nil];

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.

- (void)buttonPressed:(UIButton *)button
  if (button == testButton)
    // Store username to keychain 	
    if ([username text])
      [keychain setObject:[username text] forKey:(id)kSecAttrAccount];
    // Store password to keychain
    if ([password text])
      [keychain setObject:[password text] forKey:(id)kSecValueData];    	    
Reading from the Keychain

To populate the textfields with stored keychain items at application startup, once the textfields are defined, I read the two key-value pairs:

// Get username from keychain (if it exists)
[username setText:[keychain objectForKey:(id)kSecAttrAccount]];
NSLog(@"username: %@", [username text]);

For the password, I request the key kSecValueData:

// Get password from keychain (if it exists)  
[password setText:[keychain objectForKey:(id)kSecValueData]];
NSLog(@"password: %@", [password text]);

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

  • 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).
Apple Keychain Resources

Keychain Services Programming Guide

GenericKeychain Example (source code)

Keychain Xcode Project

Download the demo project: – Store Username and Password to Keychain


  1. Are you sure about the keychain code not running in the simulator? Because that has not been my experience.

    Also, you say there is no API to remove items from the keychain, but what about SecItemDelete? Did you just mean “no API in the KeychainItemWrapper class”?

    • The code ran in the simulator, however, when restarting the app, the values came back empty. Can you set and retrieve the values across app restarts (I am running Xcode 3.2.5).

      On removing items, I’ve changed up to description to be clearer, thanks for pointing this out.

      • Hi John,

        Thanks for your post.
        The values across app restarts in simulator working fine for me. (I’m using XCode 4)

  2. I’ve never had any problem with app restarts, but I’m using the primitives and not the wrapper class, so that might be the difference.

  3. Thanks for gr8 post!!!

    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….

  4. I’m getting an error in the NSAssert( result == noErr, @”Couldn’t add the Keychain Item.” ); line in KeyChainitemWrapper.m file. I have done exactly as you said, but maybe I’m missing something?

  5. I had implemented the keychain functionality in my app.

    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..

    Can anyone please help me for this??

  6. 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?

Comments are closed.