美文网首页
存储用户的敏感信息

存储用户的敏感信息

作者: 谢涙 | 来源:发表于2017-03-27 17:01 被阅读50次

    使用keychain来存储,也就是钥匙串,使用keychain需要导入Security框架

    自定义一个keychain的类

    #import@implementationYCKKeyChain+ (NSMutableDictionary*)getKeychainQuery:(NSString*)service {return[NSMutableDictionarydictionaryWithObjectsAndKeys:            (__bridge_transferid)kSecClassGenericPassword,(__bridge_transferid)kSecClass,            service, (__bridge_transferid)kSecAttrService,            service, (__bridge_transferid)kSecAttrAccount,            (__bridge_transferid)kSecAttrAccessibleAfterFirstUnlock,(__bridge_transferid)kSecAttrAccessible,nil];}+ (void)save:(NSString*)service data:(id)data {// 获得搜索字典NSMutableDictionary*keychainQuery = [selfgetKeychainQuery:service];// 添加新的删除旧的SecItemDelete((__bridge_retainedCFDictionaryRef)keychainQuery);// 添加新的对象到字符串[keychainQuery setObject:[NSKeyedArchiverarchivedDataWithRootObject:data] forKey:(__bridge_transferid)kSecValueData];// 查询钥匙串SecItemAdd((__bridge_retainedCFDictionaryRef)keychainQuery,NULL);}+ (id)load:(NSString*)service {idret =nil;NSMutableDictionary*keychainQuery = [selfgetKeychainQuery:service];// 配置搜索设置[keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge_transferid)kSecReturnData];    [keychainQuery setObject:(__bridge_transferid)kSecMatchLimitOne forKey:(__bridge_transferid)kSecMatchLimit];CFDataRefkeyData =NULL;if(SecItemCopyMatching((__bridge_retainedCFDictionaryRef)keychainQuery, (CFTypeRef*)&keyData) == noErr) {@try{            ret = [NSKeyedUnarchiverunarchiveObjectWithData:(__bridge_transferNSData*)keyData];        }@catch(NSException*e) {NSLog(@"Unarchive of %@ failed: %@", service, e);        }@finally{        }    }returnret;}+ (void)delete:(NSString*)service {NSMutableDictionary*keychainQuery = [selfgetKeychainQuery:service];    SecItemDelete((__bridge_retainedCFDictionaryRef)keychainQuery);}

    在别的类实现存储,加载,删除敏感信息方法

    // 用来标识这个钥匙串staticNSString*constKEY_IN_KEYCHAIN =@"com.yck.app.allinfo";// 用来标识密码staticNSString*constKEY_PASSWORD =@"com.yck.app.password";+ (void)savePassWord:(NSString*)password{NSMutableDictionary*passwordDict = [NSMutableDictionarydictionary];    [passwordDict setObject:password forKey:KEY_PASSWORD];    [YCKKeyChain save:KEY_IN_KEYCHAIN data:passwordDict];}+ (id)readPassWord{NSMutableDictionary*passwordDict = (NSMutableDictionary*)[YCKKeyChain load:KEY_IN_KEYCHAIN];return[passwordDict objectForKey:KEY_PASSWORD];}+ (void)deletePassWord{    [YCKKeyChain delete:KEY_IN_KEYCHAIN];}

    相关文章

      网友评论

          本文标题:存储用户的敏感信息

          本文链接:https://www.haomeiwen.com/subject/bjvrottx.html