Simple iPhone keychain access

Source: Internet
Author: User

From: http://useyourloaf.com/blog/2010/03/29/simple-iphone-keychain-access.html

The keychain is about the only place that an iPhone application can safely store data that will be preserved into ss a re-installation of the application. each iPhone application gets its own set of keychain items which are backed up whenever the user backs
Up the device via iTunes. the backup data is encrypted as part of the backup so that it remains secure even if somebody gets access to the backup data. this makes it very attractive to store sensitive data such as passwords, license keys, etc.

The only problem is that accessing the keychain services is complicated and even the generickeychain example code is hard to follow. I hate to include cut
And pasted code into my application, especially when I do not understand it. instead I have gone back to basics to build up a simple iPhone keychain access example that does just what I want and not much more.

In fact all I really want to be able to do is securely store a password string for my application and be able to retrieve it a later date.

Getting started

A couple of housekeeping items to get started:

  • Add the "security. Framework" framework to your iPhone application
  • Include the header file <Security/security. h>

Note that the security framework is a good old fashioned C framework so no objective-C style methods CILS. Also it will only work on the device not in the iPhone simulator.

The Basic Search dictionary

All of the callto the keychain services make use of a dictionary to define the attributes of the keychain item you want to find, create, update or delete. so the first thing we will do is define a function to allocate and construct this dictionary for us:

static NSString *serviceName = @"com.mycompany.myAppServiceName";- (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier {  NSMutableDictionary *searchDictionary = [[NSMutableDictionary alloc] init];    [searchDictionary setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];  NSData *encodedIdentifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];  [searchDictionary setObject:encodedIdentifier forKey:(id)kSecAttrGeneric];  [searchDictionary setObject:encodedIdentifier forKey:(id)kSecAttrAccount];  [searchDictionary setObject:serviceName forKey:(id)kSecAttrService];  return searchDictionary;}

The dictionary contains three items. The first with key ksecclass defines the class of the keychain item we will
Be dealing with. I want to store a password in the keychain so I use the value ksecclassgenericpassword for
Value.

The second item in the dictionary with key ksecattrgeneric is what we will use to identify the keychain item. It
Can be any value we choose such as "password" or "licensekey ",
Etc. to be clear this is not the actual value of the password just a label we will attach to this keychain item so we can find it later. in theory our application cocould store a number of passwords in the keychain so we need to have a way to identify this particle
One from the others. The identifier has to be encoded before being added to the dictionary

The combination of the final two attributes ksecattraccount and ksecattrservice shocould
Be set to something unique for this keychain. In this example I set the service name to a static string and reuse the identifier as the account name.

You can use multiple attributes for a given class of item. Some of the other attributes that we cocould also use for theksecclassgenericpassword item
Include an account name, description, etc. However by using just a single attribute we can simplify the rest of the code.

Searching the keychain

To find out if our password already exists in the keychain (and what the value of the password is) We use thesecitemcopymatching function.
But first we add a couple of extra items to our basic search dictionary:

- (NSData *)searchKeychainCopyMatching:(NSString *)identifier {  NSMutableDictionary *searchDictionary = [self newSearchDictionary:identifier];  // Add search attributes  [searchDictionary setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];  // Add search return types  [searchDictionary setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];  NSData *result = nil;  OSStatus status = SecItemCopyMatching((CFDictionaryRef)searchDictionary,                                        (CFTypeRef *)&result);  [searchDictionary release];  return result;}

The first attribute we add to the dictionary is to limit the number of search results that get returned. We are looking for a single entry so we set the attribute ksecmatchlimit to ksecmatchlimitone.

The next attribute determines how the result is returned. Since in our simple case we are expecting only a single attribute to be returned (the password) We can set the attribute ksecreturndata to kcfbooleantrue.
This means we will get an nsdata reference back that we can access directly.

If we were storing and searching for a keychain item with multiple attributes (for example if we were storing an account name and password in the same keychain item) We wocould need to add the attribute ksecreturnattributesand
The result wocould be a dictionary of attributes.

Now with the search dictionary set up we call the secitemcopymatching function and if our item exists in the keychain
The value of the password is returned to in the nsdata block. To get the actual decoded string you cocould do something like:

  NSData *passwordData = [self searchKeychainCopyMatching:@"Password"];  if (passwordData) {    NSString *password = [[NSString alloc] initWithData:passwordData                                           encoding:NSUTF8StringEncoding];    [passwordData release];  }
Creating an item in the keychain

Adding an item is almost the same as the previous examples should t that we need to set the value of the password we want to store.

- (BOOL)createKeychainValue:(NSString *)password forIdentifier:(NSString *)identifier {  NSMutableDictionary *dictionary = [self newSearchDictionary:identifier];  NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];  [dictionary setObject:passwordData forKey:(id)kSecValueData];  OSStatus status = SecItemAdd((CFDictionaryRef)dictionary, NULL);  [dictionary release];  if (status == errSecSuccess) {    return YES;  }  return NO;}

To set the value of the password we add the attribute ksecvaluedata to our search dictionary making sure we encode
The string and then call secitemadd passing the dictionary as the first argument. If the item already exists in
The keychain this will fail.

Updating a keychain item

Updating a keychain is similar to adding an item before t that a separate dictionary is used to contain the attributes to be updated. since in our case we are only updating a single attribute (the password) This is easy:

- (BOOL)updateKeychainValue:(NSString *)password forIdentifier:(NSString *)identifier {  NSMutableDictionary *searchDictionary = [self newSearchDictionary:identifier];  NSMutableDictionary *updateDictionary = [[NSMutableDictionary alloc] init];  NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];  [updateDictionary setObject:passwordData forKey:(id)kSecValueData];  OSStatus status = SecItemUpdate((CFDictionaryRef)searchDictionary,                                  (CFDictionaryRef)updateDictionary);  [searchDictionary release];  [updateDictionary release];  if (status == errSecSuccess) {    return YES;  }  return NO;}
Deleting an item from the keychain

The final (and easiest) operation is to delete an item from the keychain using the secitemdelete function and our
Usual search dictionary:

- (void)deleteKeychainValue:(NSString *)identifier {  NSMutableDictionary *searchDictionary = [self newSearchDictionary:identifier];  SecItemDelete((CFDictionaryRef)searchDictionary);  [searchDictionary release];}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.