Simple iPhone Keychain Access

Mar 29th, 2010 9:14 pm

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 <Security/Security.h>

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:

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

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

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

- (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];
}

Simple iPhone Keychain Access的更多相关文章

  1. Generate a Certificate Signing Request (CSR) in macOS Keychain Access

    macOS 10.14 (Mojave) 1. Open the Keychain Access application, located at /Applications/Utilities/Key ...

  2. Keychain group access

    Keychain group access Apr 3, 2010 · 3 minute read · Comments keychain Since iPhone OS 3.0 it has bee ...

  3. iOS 7.0获取iphone UDID 【转】

    iOS 7.0 iOS 7中苹果再一次无情的封杀mac地址,使用之前的方法获取到的mac地址全部都变成了02:00:00:00:00:00.有问题总的解决啊,于是四处查资料,终于有了思路是否可以使用K ...

  4. 【转】如何使用KeyChain保存和获取UDID

    本文是iOS7系列文章第一篇文章,主要介绍使用KeyChain保存和获取APP数据,解决iOS7上获取不变UDID的问题.并给出一个获取UDID的工具类,使用方便,只需要替换两个地方即可. 一.iOS ...

  5. iPhone OS 开发 - 了解并解决代码签名问题

    译者:Jestery 发表时间:2010-04-24浏览量:21082评论数:0挑错数:0 了解并解决代码签名问题 (为保持跟开发环境以及APPLE开发者社区网站结构对应,一些名词未作翻译) 绝大多数 ...

  6. (转)iOS keychain API及其封装

    一. Keychain API KeyChain中item的结构为: 1.增加keychain Item OSStatus SecItemAdd (CFDictionaryRef attributes ...

  7. iPhone应用提交流程:如何将App程序发布到App Store?

    对于刚加入iOS应用开发行列的开发者来说,终于经过艰苦的Coding后完成了第一个应用后最重要的历史时刻就是将应用程序提交到iTunes App Store.Xcode 4.2开发工具已经把App提交 ...

  8. iPhone 真机调试应用程序

    原文:http://blog.sina.com.cn/s/blog_68e753f70100r3w5.html 真机调试iphone应用程序 1.真机调试流程概述 1)       真机调试应用程序, ...

  9. Keychain 浅析

    什么是Keychain? 根据苹果的介绍,iOS设备中的Keychain是一个安全的存储容器,可以用来为不同应用保存敏感信息比如用户名,密码,网络密码,认证令牌.苹果自己用keychain来保存Wi- ...

随机推荐

  1. [atAGC049F]Happy Sequence

    定义$L=2\cdot 10^{5}$,$g(x)=\sum_{i=1}^{n}|b_{i}-x|-|a_{i}-x|$,则合法当且仅当$\forall 0\le x\le L,g(x)\ge 0$, ...

  2. ICCV 2021口罩人物身份鉴别全球挑战赛冠军方案分享

    1. 引言 10月11-17日,万众期待的国际计算机视觉大会 ICCV 2021 (International Conference on Computer Vision) 在线上如期举行,受到全球计 ...

  3. ICCV2021 | SOTR:使用transformer分割物体

    ​前言 本文介绍了现有实例分割方法的一些缺陷,以及transformer用于实例分割的困难,提出了一个基于transformer的高质量实例分割模型SOTR. 经实验表明,SOTR不仅为实例分割提供了 ...

  4. centos与ubuntu安装及相关问题解答

    1.按系列罗列Linux的发行版,并描述不同发行版之间的联系与区别. 答:Linus的发行版本有slackware,debian,redhat,Alpine,ArchLinux,Gentoo,LFS, ...

  5. Anaconda 镜像配置

    镜像源 清华大学: https://mirrors.tuna.tsinghua.edu.cn/help/anaconda/ 北京外国语大学: https://mirrors.bfsu.edu.cn/h ...

  6. perl 获取目录信息

    1 #!/usr/bin/perl -w 2 use strict; 3 use FindBin qw($Bin $Script); 4 5 my $rp=$Bin; 6 print "th ...

  7. linux中对errno是EINTR的处理

    慢系统调用(slow system call):此术语适用于那些可能永远阻塞的系统调用.永远阻塞的系统调用是指调用有可能永远无法返回,多数网络支持函数都属于这一类.如:若没有客户连接到服务器上,那么服 ...

  8. 在Idea上用JDBC连接mysql数据库

    一.前言 本次操作建立在idea中java环境已配置的基础上 二.操作步骤 1.建立Web项目后,添加驱动包 mysql-connector-java-5.0.8-bin.jar (1)下载mysql ...

  9. 学习java的第十天

    一.今日收获 1.java完全学习手册第二章2.9程序流程控制中的选择结构与顺序结构的例题 2.观看哔哩哔哩上的教学视频 二.今日问题 1.例题的问题不大,需要注意大小写,新的语句记忆不牢 2.哔哩哔 ...

  10. 日常Java 2021/11/2

    Java提供了一种对象序列化的机制,该机制中,一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据.有关对象的类型的信息和存储在对象中数据的类型.将序列化对象写入文件之后,可以从文件中读取出来 ...