Table of Contents
Getting Started
The Basic Search Dictionary
Searching the keychain
Creating an item in the keychain
Updating a keychain item
Deleting an item from the keychain
Home Database Mysql Tutorial Simple iPhone Keychain Access

Simple iPhone Keychain Access

Jun 07, 2016 pm 03:49 PM
access iphone simple

The keychain is about the only place that an iPhone application can safely store data that will be preserved across a re-installation of the application. Each iPhone application gets its own set of keychain items which are backed up whenev

The keychain is about the only place that an iPhone application can safely store data that will be preserved across 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

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

The Basic Search Dictionary

All of the calls to 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<code>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;

}

</code>

Copy after login

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 the 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 could store a number of passwords in the keychain so we need to have a way to identify this particular 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 should 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 could also use for the kSecClassGenericPassword 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 the SecItemCopyMatching function. But first we add a couple of extra items to our basic search dictionary:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<code>- (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;

}

</code>

Copy after login

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 would need to add the attribute kSecReturnAttributes and the result would 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 could do something like:

1

2

3

4

5

6

7

<code>  NSData *passwordData = [self searchKeychainCopyMatching:@"Password"];

  if (passwordData) {

    NSString *password = [[NSString alloc] initWithData:passwordData

                                           encoding:NSUTF8StringEncoding];

    [passwordData release];

  }

</code>

Copy after login

Creating an item in the keychain

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<code>- (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;

}

</code>

Copy after login

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 except 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<code>- (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;

}

</code>

Copy after login

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:

1

2

3

4

5

6

7

<code>- (void)deleteKeychainValue:(NSString *)identifier {

 

  NSMutableDictionary *searchDictionary = [self newSearchDictionary:identifier];

  SecItemDelete((CFDictionaryRef)searchDictionary);

  [searchDictionary release];

}

</code>

Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to convert deepseek pdf How to convert deepseek pdf Feb 19, 2025 pm 05:24 PM

DeepSeek cannot convert files directly to PDF. Depending on the file type, you can use different methods: Common documents (Word, Excel, PowerPoint): Use Microsoft Office, LibreOffice and other software to export as PDF. Image: Save as PDF using image viewer or image processing software. Web pages: Use the browser's "Print into PDF" function or the dedicated web page to PDF tool. Uncommon formats: Find the right converter and convert it to PDF. It is crucial to choose the right tools and develop a plan based on the actual situation.

Gate.io trading platform official app download and installation address Gate.io trading platform official app download and installation address Feb 13, 2025 pm 07:33 PM

This article details the steps to register and download the latest app on the official website of Gate.io. First, the registration process is introduced, including filling in the registration information, verifying the email/mobile phone number, and completing the registration. Secondly, it explains how to download the Gate.io App on iOS devices and Android devices. Finally, security tips are emphasized, such as verifying the authenticity of the official website, enabling two-step verification, and being alert to phishing risks to ensure the safety of user accounts and assets.

Anbi app official download v2.96.2 latest version installation Anbi official Android version Anbi app official download v2.96.2 latest version installation Anbi official Android version Mar 04, 2025 pm 01:06 PM

Binance App official installation steps: Android needs to visit the official website to find the download link, choose the Android version to download and install; iOS search for "Binance" on the App Store. All should pay attention to the agreement through official channels.

Download link of Ouyi iOS version installation package Download link of Ouyi iOS version installation package Feb 21, 2025 pm 07:42 PM

Ouyi is a world-leading cryptocurrency exchange with its official iOS app that provides users with a convenient and secure digital asset management experience. Users can download the Ouyi iOS version installation package for free through the download link provided in this article, and enjoy the following main functions: Convenient trading platform: Users can easily buy and sell hundreds of cryptocurrencies on the Ouyi iOS app, including Bitcoin and Ethereum. and Dogecoin. Safe and reliable storage: Ouyi adopts advanced security technology to provide users with safe and reliable digital asset storage. 2FA, biometric authentication and other security measures ensure that user assets are not infringed. Real-time market data: Ouyi iOS app provides real-time market data and charts, allowing users to grasp encryption at any time

How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? How to solve the problem of 'Undefined array key 'sign'' error when calling Alipay EasySDK using PHP? Mar 31, 2025 pm 11:51 PM

Problem Description When calling Alipay EasySDK using PHP, after filling in the parameters according to the official code, an error message was reported during operation: "Undefined...

How to solve the problem of third-party interface returning 403 in Node.js environment? How to solve the problem of third-party interface returning 403 in Node.js environment? Mar 31, 2025 pm 11:27 PM

Solve the problem of third-party interface returning 403 in Node.js environment. When we use Node.js to call third-party interfaces, we sometimes encounter an error of 403 from the interface returning 403...

How to install and register an app for buying virtual coins? How to install and register an app for buying virtual coins? Feb 21, 2025 pm 06:00 PM

Abstract: This article aims to guide users on how to install and register a virtual currency trading application on Apple devices. Apple has strict regulations on virtual currency applications, so users need to take special steps to complete the installation process. This article will elaborate on the steps required, including downloading the application, creating an account, and verifying your identity. Following this article's guide, users can easily set up a virtual currency trading app on their Apple devices and start trading.

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

See all articles