iOS Keychain KeychainItemWrapper And SFHFKeychainUtils

对于一些私密信息,比如密码、证书等等,就需要使用更为安全的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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值