iOS Keychain KeychainItemWrapper And SFHFKeychainUtils

来源:互联网 发布:halcon机器视觉软件 编辑:程序博客网 时间:2024/05/17 23:42

对于一些私密信息,比如密码、证书等等,就需要使用更为安全的keychain了。keychain里保存的信息不会因App被删除而丢失,在用户重新安装App后依然有效,数据还在。

1.在网上下载SFHFKeychainUtils 或者KeychainItemWrapper 代码 ,简单浏览一下 (demo下载地址 http://download.csdn.net/detail/u011715727/8217941 )

主要是存储,删除,获取这个闭合流程。只测试了模拟器,可以不需要Security.framework,真机需要正确有效的Bundle identifier.

2.代码: 初始化

KeychainItemWrapper 需要新建一个KeychainAccessGroups.plist文件,结构如下:

Root                       Dictionary

  keychain-access-groups    Array 

     item0                  string   YOUR_APP_ID_HERE.com.youcompany.KeychainDemo


加入 Security.framework

appdelegate.m

#import "KeychainItemWrapper.h"

    KeychainItemWrapper *passwordWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Password" accessGroup:nil];

    KeychainItemWrapper *accountWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Account Number" accessGroup:@"YOUR_APP_ID_HERE.com.youcompany.KeychainDemo"];

你需要调用的.m文件

#import "SFHFKeychainUtils.h"

#import "KeychainItemWrapper.h"

#define ServiceName @"com.youcompany.KeychainDemo"

......{

    KeychainItemWrapper *accountItem_keyChain;

    KeychainItemWrapper *passwordItem_keyChain;

}

a. 存储

   //方法一

        [accountItem_keyChain setObject:userNameTextField.text forKey:kSecAttrAccount];

        [passwordItem_keyChain setObject:userPasscodeTextField.text forKey:kSecValueData];


        //方法二

        [SFHFKeychainUtils storeUsername:@"userName" andPassword:userNameTextField.text forServiceName:ServiceName updateExisting:@"" error:nil];

        [SFHFKeychainUtils storeUsername:@"userPassword" andPassword:userPasscodeTextField.text forServiceName:ServiceName updateExisting:@"" error:nil];

b.删除

   //方法一

        [accountItem_keyChain resetKeychainItem];

        [passwordItem_keyChain resetKeychainItem];

    

        //方法二

        [SFHFKeychainUtils deleteItemForUsername:@"userName" andServiceName:ServiceName error:nil];

        [SFHFKeychainUtils deleteItemForUsername:@"userPassword" andServiceName:ServiceName error:nil];

c.获取

    NSString *nameString;

    NSString *passwordString;

        //方法一

        nameString = [accountItem_keyChain objectForKey:kSecAttrAccount];

        passwordString = [passwordItem_keyChain objectForKey:kSecValueData];

          //方法二

        nameString = [SFHFKeychainUtils getPasswordForUsername:@"userName" andServiceName:ServiceName error:nil];

        passwordString = [SFHFKeychainUtils getPasswordForUsername:@"userPassword" andServiceName:ServiceName error:nil];


完毕,如有错误,早点请指正,减少误导。
0 0
原创粉丝点击