목차
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
데이터 베이스 MySQL 튜토리얼 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>

로그인 후 복사

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 *)&amp;result);

 

  [searchDictionary release];

  return result;

}

</code>

로그인 후 복사

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>

로그인 후 복사

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>

로그인 후 복사

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>

로그인 후 복사

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>

로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

DeepSeek PDF를 변환하는 방법 DeepSeek PDF를 변환하는 방법 Feb 19, 2025 pm 05:24 PM

DeepSeek PDF를 변환하는 방법

새로운 카메라, A18 Pro SoC 및 더 큰 화면을 갖춘 iPhone 16 Pro 및 iPhone 16 Pro Max 공식 새로운 카메라, A18 Pro SoC 및 더 큰 화면을 갖춘 iPhone 16 Pro 및 iPhone 16 Pro Max 공식 Sep 10, 2024 am 06:50 AM

새로운 카메라, A18 Pro SoC 및 더 큰 화면을 갖춘 iPhone 16 Pro 및 iPhone 16 Pro Max 공식

iOS 18 RC에서 발견된 iPhone 부품 활성화 잠금 - 사용자 보호를 가장하여 판매된 수리 권리에 대한 Apple의 최근 타격일 수 있습니다. iOS 18 RC에서 발견된 iPhone 부품 활성화 잠금 - 사용자 보호를 가장하여 판매된 수리 권리에 대한 Apple의 최근 타격일 수 있습니다. Sep 14, 2024 am 06:29 AM

iOS 18 RC에서 발견된 iPhone 부품 활성화 잠금 - 사용자 보호를 가장하여 판매된 수리 권리에 대한 Apple의 최근 타격일 수 있습니다.

iPhone 부품 활성화 잠금은 사용자 보호를 가장하여 판매된 수리 권리에 대한 Apple의 최근 타격일 수 있습니다. iPhone 부품 활성화 잠금은 사용자 보호를 가장하여 판매된 수리 권리에 대한 Apple의 최근 타격일 수 있습니다. Sep 13, 2024 pm 06:17 PM

iPhone 부품 활성화 잠금은 사용자 보호를 가장하여 판매된 수리 권리에 대한 Apple의 최근 타격일 수 있습니다.

Gate.io 거래 플랫폼 공식 앱 다운로드 및 설치 주소 Gate.io 거래 플랫폼 공식 앱 다운로드 및 설치 주소 Feb 13, 2025 pm 07:33 PM

Gate.io 거래 플랫폼 공식 앱 다운로드 및 설치 주소

LCD 아이폰이 역사가 되다! 애플은 완전히 버려질 것이다: 시대의 종말 LCD 아이폰이 역사가 되다! 애플은 완전히 버려질 것이다: 시대의 종말 Sep 03, 2024 pm 09:38 PM

LCD 아이폰이 역사가 되다! 애플은 완전히 버려질 것이다: 시대의 종말

가상 코인 구매를위한 앱을 설치하고 등록하는 방법은 무엇입니까? 가상 코인 구매를위한 앱을 설치하고 등록하는 방법은 무엇입니까? Feb 21, 2025 pm 06:00 PM

가상 코인 구매를위한 앱을 설치하고 등록하는 방법은 무엇입니까?

ANBI 앱 공식 다운로드 v2.96.2 최신 버전 설치 Anbi 공식 안드로이드 버전 ANBI 앱 공식 다운로드 v2.96.2 최신 버전 설치 Anbi 공식 안드로이드 버전 Mar 04, 2025 pm 01:06 PM

ANBI 앱 공식 다운로드 v2.96.2 최신 버전 설치 Anbi 공식 안드로이드 버전

See all articles