码迷,mamicode.com
首页 > 其他好文 > 详细

简单实现KeyChain实例

时间:2014-12-29 13:38:06      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

目录结构如下:

技术分享

AppDelegate.m

 1 //
 2 //  AppDelegate.m
 3 //  KeyChain
 4 //
 5 //  Created by apple on 14-12-26.
 6 //  Copyright (c) 2014年 ll. All rights reserved.
 7 //
 8 
 9 #import "AppDelegate.h"
10 
11 @interface AppDelegate ()
12 
13 @end
14 
15 @implementation AppDelegate
16 
17 
18 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
19     // Override point for customization after application launch.
20     ViewController *vc = [[ViewController alloc] init];
21     self.window.rootViewController = vc;
22     [self.window makeKeyAndVisible];
23     return YES;
24 }
25 
26 - (void)applicationWillResignActive:(UIApplication *)application {
27     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
28     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
29 }
30 
31 - (void)applicationDidEnterBackground:(UIApplication *)application {
32     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
33     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
34 }
35 
36 - (void)applicationWillEnterForeground:(UIApplication *)application {
37     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
38 }
39 
40 - (void)applicationDidBecomeActive:(UIApplication *)application {
41     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
42 }
43 
44 - (void)applicationWillTerminate:(UIApplication *)application {
45     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
46 }
47 
48 @end

KeyChain.h

 1 //
 2 //  KeyChain.h
 3 //  KeyChain
 4 //
 5 //  Created by apple on 14-12-26.
 6 //  Copyright (c) 2014年 ll. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 #import <Security/Security.h>
11 
12 @interface KeyChain : NSObject
13 
14 + (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier;
15 
16 + (void)save:(NSString *)service data:(id)data;
17 
18 + (id)load:(NSString *)service;
19 
20 + (void)delete:(NSString *)service;
21 
22 @end

KeyChain.m

 1 //
 2 //  KeyChain.m
 3 //  KeyChain
 4 //
 5 //  Created by apple on 14-12-26.
 6 //  Copyright (c) 2014年 ll. All rights reserved.
 7 //
 8 /**
 9  *__bridge_transfer , __bridge_retained c和oc类型之间转换,,可统一使用__bridge替换
10  */
11 #import "KeyChain.h"
12 static NSString *serviceName = @"com.mycompany.myAppServiceName";
13 
14 @implementation KeyChain
15 
16 + (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier
17 {
18     
19     NSMutableDictionary * searchDictionary = [[NSMutableDictionary alloc] init];
20     NSData *encodeInditifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];
21     [searchDictionary setObject:(__bridge_transfer id)kSecClassGenericPassword
22                          forKey:(__bridge_transfer id)kSecClass];
23     [searchDictionary setObject:encodeInditifier forKey:(__bridge_transfer id)kSecAttrGeneric];
24     [searchDictionary setObject:encodeInditifier forKey:(__bridge_transfer id)kSecAttrAccount];
25     [searchDictionary setObject:(__bridge_transfer id)kSecAttrAccessibleAfterFirstUnlock
26                          forKey:(__bridge_transfer id)kSecAttrAccessible];
27     
28     //[searchDictionary setObject:serviceName forKey:(__bridge id)kSecAttrService];
29     
30     return searchDictionary;
31 }
32 
33 +(void)save:(NSString *)service data:(id)data
34 {
35     NSMutableDictionary *keyChainQuery = [self newSearchDictionary:service];
36     /**
37      *  delete old
38      */
39     SecItemDelete((__bridge_retained CFDictionaryRef)keyChainQuery);
40     [keyChainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data]
41                       forKey:(__bridge_transfer id)kSecValueData];
42     /**
43      *  add new
44      */
45     SecItemAdd((__bridge_retained CFDictionaryRef)keyChainQuery, nil);
46     
47 }
48 
49 +(id)load:(NSString *)service
50 {
51     id ret = nil;
52     NSMutableDictionary *keyChainQuery = [self newSearchDictionary:service];
53     [keyChainQuery setObject:(id)kCFBooleanTrue
54                       forKey:(__bridge_transfer id)kSecReturnData];
55     [keyChainQuery setObject:(__bridge_transfer id)kSecMatchLimitOne
56                       forKey:(__bridge_transfer id)kSecMatchLimit];
57     CFDataRef keyData = NULL;
58     
59     if (SecItemCopyMatching((__bridge_retained CFDictionaryRef)keyChainQuery, (CFTypeRef*)&keyData) == noErr)
60     {
61         ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData*)keyData];
62     }
63     
64 //    if (keyData) {
65 //        
66 //        CFRelease(keyData);
67 //    }
68 //    
69     
70     return ret;
71 }
72 
73 +(void)delete:(NSString *)service
74 {
75     NSMutableDictionary *keyChainQuery = [self newSearchDictionary:service];
76     
77     SecItemDelete((__bridge_retained CFDictionaryRef)keyChainQuery);
78     
79 }
80 
81 
82 @end

ViewController.h

 1 //
 2 //  ViewController.h
 3 //  KeyChain
 4 //
 5 //  Created by apple on 14-12-26.
 6 //  Copyright (c) 2014年 ll. All rights reserved.
 7 //
 8 
 9 #import <UIKit/UIKit.h>
10 #import "KeyChain.h"
11 
12 @interface ViewController : UIViewController
13 
14 + (void)savePassWord:(NSString *)password;
15 
16 + (id)readPassWord;
17 
18 + (void)deletePassWord;
19 
20 
21 @end

 

ViewController.m

  1 //
  2 //  ViewController.m
  3 //  KeyChain
  4 //
  5 //  Created by apple on 14-12-26.
  6 //  Copyright (c) 2014年 ll. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 static NSString * const KEY_IN_KEYCHAIN = @"com.wuqian.app.allinfo";// 字典在keychain中的key
 11 static NSString * const KEY_PASSWORD = @"com.wuqian.app.password"; //  密码在字典中的key
 12 
 13 @interface ViewController ()
 14 {
 15     UITextField * _field; // 输入密码
 16     UILabel *_psw;        // 显示密码
 17 }
 18 
 19 @end
 20 
 21 @implementation ViewController
 22 
 23 - (void)viewDidLoad {
 24     [super viewDidLoad];
 25     
 26     self.view.backgroundColor = [UIColor whiteColor];
 27     
 28     UILabel * labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 30)];
 29     labelName.text = @"密码是:";
 30     
 31     
 32     _field = [[UITextField alloc] initWithFrame:CGRectMake(100, 80, 200, 30)];
 33     _field.placeholder = @"请输入密码";
 34     _field.borderStyle = UITextBorderStyleRoundedRect;
 35     
 36     _psw = [[UILabel alloc] initWithFrame:CGRectMake(100, 30, 200, 30)];
 37     _psw.backgroundColor = [UIColor yellowColor];
 38 
 39     UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
 40     btn.frame =CGRectMake(100, 160, 200, 30);
 41     btn.backgroundColor = [UIColor colorWithRed:0 green:0.4 blue:0.1 alpha:0.8];
 42     btn.tintColor = [UIColor redColor];
 43     [btn setTitle:@"submit" forState:UIControlStateNormal];
 44     //[btn setTitle:@"正在提交" forState:UIControlStateSelected];
 45     
 46     [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
 47 //    UIGestureRecognizer *tap = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
 48 //    [self.view addGestureRecognizer:tap];
 49     
 50     
 51     
 52     [self.view addSubview:btn];
 53     [self.view addSubview:_field];
 54     [self.view addSubview:labelName];
 55     [self.view addSubview:_psw];
 56     // Do any additional setup after loading the view, typically from a nib.
 57 }
 58 
 59 - (void)didReceiveMemoryWarning {
 60     [super didReceiveMemoryWarning];
 61     // Dispose of any resources that can be recreated.
 62 }
 63 //- (void)tap:(UIGestureRecognizer*)gr
 64 //{
 65 //
 66 //    
 67 //    [_field resignFirstResponder];
 68 //}
 69 
 70 - (void)btnClick:(id)sender
 71 {
 72     [ViewController savePassWord:_field.text];
 73     _psw.text = [ViewController readPassWord];
 74 
 75     if (![_field isExclusiveTouch]) {
 76         //Setting this property to YES causes the receiver to block the delivery of touch events to other views in the same window. The default value of this property is NO.
 77         [_field resignFirstResponder];// 收回键盘
 78 
 79     }
 80     
 81 }
 82 
 83 + (void)savePassWord:(NSString *)password
 84 {
 85     NSMutableDictionary *usernamepasswordKVPairs = [[NSMutableDictionary alloc] init];
 86     [usernamepasswordKVPairs setObject:password forKey:KEY_PASSWORD];
 87     [KeyChain save:KEY_IN_KEYCHAIN data:usernamepasswordKVPairs];
 88 }
 89 
 90 + (id)readPassWord
 91 {
 92     NSMutableDictionary *usernamepasswordKVPairs = (NSMutableDictionary *)[KeyChain load:KEY_IN_KEYCHAIN];
 93     
 94     return [usernamepasswordKVPairs objectForKey:KEY_PASSWORD];
 95     
 96 }
 97 
 98 + (void)deletePassWord
 99 {
100     [KeyChain delete:KEY_IN_KEYCHAIN];
101     
102 }
103 
104 @end

运行效果:

技术分享

 
 

简单实现KeyChain实例

标签:

原文地址:http://www.cnblogs.com/liuziyu/p/4191332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!