Simple iPhone Keychain Access

本文介绍如何利用iPhone的密钥链服务安全地存储和检索应用敏感数据,如密码等。文章详细解释了创建、搜索、更新及删除密钥链项的过程,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



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



内容概要:本文档是Kenwood TK-6110 VHF FM收发器的操作手册,详细介绍了设备的基本功能、安装步骤和操作指南。手册首先感谢用户选择Kenwood产品,并强调了设备的安全性和合规性,包括FCC警告和政府法律禁止未经授权的无线电台操作。接着,手册逐步指导用户进行设备的拆箱检查、安装准备(如工具、电源连接)、安装步骤以及熟悉设备的前面板、后面板和麦克风布局。此外,还涵盖了基本操作(如开关机、音量调整、频道选择和通话)以及辅助功能(如定时断电、忙道锁定、双音多频呼叫等)。最后,提供了关于DTMF呼叫(手动拨号、重拨、自动拨号)的具体操作步骤。 适合人群:适用于需要使用Kenwood TK-6110 VHF FM收发器的专业用户或技术人员,特别是那些负责安装和维护移动通信设备的人员。 使用场景及目标:①帮助用户正确安装和配置Kenwood TK-6110 VHF FM收发器,确保其在车辆或其他移动平台上安全可靠地运行;②指导用户掌握设备的基本操作技能,如频道选择、通话、信号发送等;③提供详细的辅助功能设置说明,使用户能够充分利用设备的各种高级功能,如定时断电、忙道锁定、双音多频呼叫等。 其他说明:用户应仔细阅读并遵守所有安全警告和操作指南,以避免潜在的危害和法律问题。建议在安装和使用过程中咨询授权经销商或专业技术人员,以确保设备的正常运行和最佳性能。
内容概要:本文档详细介绍了一个基于MATLAB实现的Crossformer-Transformer跨变量注意力增强模型,用于多变量时间序列预测。项目旨在提升预测精度、构建高效且可扩展的深度学习架构、实现完整的模型实现与调试、深入分析变量间的时序依赖及交互机制、提升模型泛化能力和鲁棒性、促进多领域应用的智能化升级以及推动跨领域学术与技术交流。文档涵盖项目背景、目标与意义、挑战及解决方案、模型架构、代码实现、特点与创新、应用领域、注意事项、数据生成、目录结构设计、部署与应用、未来改进方向、总结与结论以及详细的程序设计思路和代码实现。 适用人群:具备一定编程基础,对深度学习、时间序列预测感兴趣的科研人员和工程师,特别是工作1-3年的研发人员。 使用场景及目标:①用于金融市场、智能制造、气象预报、交通流量、医疗健康、能源管理、生态环境、供应链等多领域的时间序列预测;②提升多变量时间序列预测的精度和泛化能力;③实现MATLAB环境下高效的模型训练与调试;④深入分析变量间的动态关系和时序依赖;⑤推动智能预测技术在实际场景中的应用与推广。 阅读建议:此资源不仅提供了完整的代码实现,还详细介绍了模型架构、训练过程和应用场景,读者在学习过程中应结合具体的应用场景进行实践,重点关注数据预处理、模型参数调整和结果解释,以确保理论与实践相结合,更好地理解和应用Crossformer-Transformer模型。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值