iOS 钥匙串的基本使用

级别: ★☆☆☆☆
标签:「钥匙串」「keychain」「iOS」
作者: WYW
审校: QiShare团队


前言 :
项目中有时会需要存储敏感信息(如密码、密钥等),苹果官方提供了一种存储机制--钥匙串(keychain)
keychain是一种存储在硬盘上的加密的数据库。这个可能是卸载App后,keychain信息还在的原因。
keychain适合存储 较小的数据量不超过上千字节或上兆字节)的内容。
笔者做了一个关于keychain的增、删、改、查的Demo(QiKeychain),给大家介绍下keychain的基本使用。

下图(确保keychain中用户的信息安全)有利于我们直观了解keychain。

Demo(QiKeychain)解读:

笔者用Demo(QiKeychain)做了4件事。

  • 增加:存储用户名、密码到keychain;
  • 查询:根据用户名从keychain中查询密码;
  • 删除:从keychain中删除用户名、密码等相应信息;
  • 修改:修改keychain中的用户名对应的密码;

Demo(QiKeychain)对keychain的操作效果如下:

  • 存储用户名 “QiShare”,密码:1234;
  • 查询用户名为“QiShare”的密码,显示密码为:1234;
  • 修改用户名“QiShare”的密码为“123456”;
  • 查询“QiShare”的密码,显示为“123456”;
  • 把“QiShare”从keychain中删除。

keychain基本使用API

keychain有四个常用的API,用于增、删、改、查keychain中的数据。
keychain中的数据子项是以item的形式存在的。
举个例子:就存储用户名、密码的情景来说,每个item包含存储的用户名和密码及其他属性信息,keychain中包含多个用户名和密码的item。

下图(把数据和属性存储到keychain中)利于我们理解存储过程

SecItemAdd:添加一个item或多个items到keychain
OSStatus SecItemAdd(CFDictionaryRef attributes, CFTypeRef * __nullable CF_RETURNS_RETAINED result)API_AVAILABLE(macos(10.6), ios(2.0));
复制代码

存储关键代码:

    NSDictionary *saveSecItems = @{(id)kSecClass: (id)kSecClassGenericPassword,(id)kSecAttrService: service,(id)kSecAttrAccount: account,(id)kSecValueData: passwordData};OSStatus saveStatus = SecItemAdd((CFDictionaryRef)saveSecItems, NULL);
复制代码
SecItemCopyMatching:返回匹配搜索查询的一个item或多个items
OSStatus SecItemCopyMatching(CFDictionaryRef query, CFTypeRef * __nullable CF_RETURNS_RETAINED result)API_AVAILABLE(macos(10.6), ios(2.0));
复制代码

查询关键代码:

  NSDictionary *matchSecItems = @{(id)kSecClass: (id)kSecClassGenericPassword,(id)kSecAttrService: service,(id)kSecAttrAccount: account,(id)kSecMatchLimit: (id)kSecMatchLimitOne,(id)kSecReturnData: @(YES)};CFTypeRef dataRef = nil;OSStatus errorCode = SecItemCopyMatching((CFDictionaryRef)matchSecItems, (CFTypeRef *)&dataRef);
复制代码
SecItemUpdate:修改匹配搜索查询的一个item或多个items
OSStatus SecItemUpdate(CFDictionaryRef query, CFDictionaryRef attributesToUpdate)API_AVAILABLE(macos(10.6), ios(2.0));
复制代码

注意:更新代码这部分,笔者开始的时候遇到一些问题,还要多谢组内成员,尤其是昆哥的指教。
SecItemUpdate接收了2个参数,query和attributesToUpdate。
第一个参数query用于查询到相应的item, 第二个参数attributesToUpdate用于传入要更新的信息。
笔者曾错误地给第二个参数attributesToUpdate传入过(id)kSecClass: (id)kSecClassGenericPassword要更改的内容。
结果报错为:
errSecNoSuchAttr = -25303, /* The specified attribute does not exist. */

更新关键代码:

    NSDictionary *queryItems = @{(id)kSecClass: (id)kSecClassGenericPassword,(id)kSecAttrService: service,(id)kSecAttrAccount: account};NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];NSDictionary *updatedItems = @{(id)kSecValueData: passwordData,};OSStatus updateStatus = SecItemUpdate((CFDictionaryRef)queryItems, (CFDictionaryRef)updatedItems);
复制代码
SecItemDelete:删除匹配搜索查询的一个item或多个items
OSStatus SecItemDelete(CFDictionaryRef query)API_AVAILABLE(macos(10.6), ios(2.0));
复制代码

删除关键代码:

    NSDictionary *deleteSecItems = @{(id)kSecClass: (id)kSecClassGenericPassword,(id)kSecAttrService: service,(id)kSecAttrAccount: account};OSStatus errorCode = SecItemDelete((CFDictionaryRef)deleteSecItems);
复制代码
显然keychain的增删改查相关的API都需要设置相应的属性字典(分别代指上述的saveSecItems 、matchSecItems 、queryItems 、updatedItems 、deleteSecItems)
  • 属性字典的key、value常用的有:(这部分内容读者也可直接看文档)
  • (id)kSecClass: (id)kSecClassGenericPassword kSecClass表示item的class (id)kSecClass的值表明一个通用的密码item笔者一般都传入kSecClassGenericPassword
  • (id)kSecAttrService: service kSecAttrService的value用于表明item的service
  • (id)kSecAttrAccount: account (id)kSecAttrAccoun的值表明item的帐户名
  • (id)kSecValueData: passwordData (id)kSecValueData表示item的数据
  • (id)kSecMatchLimit: (id)kSecMatchLimitOne, (id)kSecMatchLimit 有2个值(id)kSecMatchLimitOne、和(id)kSecMatchLimitAll kSecMatchLimitOne:表示只匹配第一个符合条件的item kSecMatchLimitAll:表示匹配不限数量的items
  • (id)kSecReturnData: @(YES) (id)kSecReturnData的值是一个Boolean类型的值用于确定是否返回item data
  • kSecClass的值表示item的class kSecClass的值表明一个通用的密码item笔者一般都传入的kSecClassGenericPassword
  • kSecClass的值表示item的class kSecClass的值表明一个通用的密码item笔者一般都传入的kSecClassGenericPassword

Demo(QiKeychain)相关代码

在Demo(QiKeychain)中,笔者对keychain相关使用的API进行了封装。获取Demo(QiKeychain)GitHub地址:QiKeychain。

注意:笔者后来封装的代码,修改了保存操作的逻辑。

修改内容为:在保存用户名密码的时候
-> 先在keychain中查询用户名是否存在
-> 若存在,就进行更新操作;
-> 若不存在就进行保存操作。

相应示意图(使用钥匙串存储网络密码)如下:

参考学习地址

  • Keychain Services
  • SAMKeychain

小编微信:可加并拉入《QiShare技术交流群》。

关注我们的途径有:
QiShare(简书)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公众号)

推荐文章:
iOS 自定义拖拽式控件:QiDragView
iOS 自定义卡片式控件:QiCardView
iOS Wireshark抓包
iOS Charles抓包
初探TCP
IP、UDP初探
奇舞周刊

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388262.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

线性回归和将线拟合到数据

Linear Regression is the Supervised Machine Learning Algorithm that predicts continuous value outputs. In Linear Regression we generally follow three steps to predict the output.线性回归是一种监督机器学习算法,可预测连续值输出。 在线性回归中&…

Spring Boot MyBatis配置多种数据库

mybatis-config.xml是支持配置多种数据库的,本文将介绍在Spring Boot中使用配置类来配置。 1. 配置application.yml # mybatis配置 mybatis:check-config-location: falsetype-aliases-package: ${base.package}.modelconfiguration:map-underscore-to-camel-case: …

小米盒子4 拆解图解_我希望当我开始学习R时会得到的盒子图解指南

小米盒子4 拆解图解Customizing a graph to transform it into a beautiful figure in R isn’t alchemy. Nonetheless, it took me a lot of time (and frustration) to figure out how to make these plots informative and publication-quality. Rather than hoarding this …

组态王仿真随机数

1、新建IO设备,选择PLC---亚控---仿真PLC,一直“下一步”。 2、在“数据词典”中新建变量“Tag1”,双击Tag1,变量类型选:I/O实数;初始值设为:0.6;最小值设为:0.5&#xf…

蓝牙一段一段_不用担心,它在那里存在了一段时间

蓝牙一段一段You’re sitting in a classroom. You look around and see your friends writing something down. It seems they are taking the exam, and they know all the answers (even Johnny who, how to say it… wasn’t the brilliant one). You realize that your ex…

Linux基础命令---ifup、ifdown

ifupifup指令用来启动网络接口设备,设备必须是定义在“/etc/sysconfig/network-scripts/ifcfg-ethX”或者“/etc/sysconfig/network”的文件。这些脚本通常使用一个参数:配置的名称(例如eth0)。在引导序列中,使用“boot”的第二个参数调用它们…

OllyDBG 入门之四--破解常用断点设

OllyDBG 入门之四--破解常用断点(转) 软件汉化2010-07-08 16:25:23 阅读76评论0 字号:大中小 订阅 bpx hmemcpy 破解万能断点,拦截内存拷贝动作 bpx Lockmytask 当你用其它断点都无效时可以试一下,这个断点拦截…

POJ1204 Word Puzzles

传送门 这题果然是AC自动机的大好题! 题目的大意是,给定一个l*c的大网格,每个格子里有一个字符,每个格子可以向八个方向形成字符串,问给定的字符串在哪里能被匹配以及在网格中出现的方向(A代表北&#xff0…

普通话测试系统_普通话

普通话测试系统Traduzido/adaptado do original por Vincius Barqueiro a partir do texto original “Writing Alt Text for Data Visualization”, escrito por Amy Cesal e publicado no blog Nightingale.Traduzido / adaptado由 VinciusBarqueiro 提供原始 文本“为数据可…

Mac OS 被XCode搞到无法正常开机怎么办?

Mac OS 被XCode搞到无法正常开机怎么办? 第一天拿到这台air的时候,迫不及待地把从别处搜集来的XCode 3.2.5iOS SDK 4.1的dmg安装了上来,结果系统直接崩溃,再开机就不能正常开机,总是碰到kernel panic。这不坑爹吗…… …

美国队长3:内战_隐藏的宝石:寻找美国最好的秘密线索

美国队长3:内战There are plenty of reasons why one would want to find solitude in the wilderness, from the therapeutic effects of being immersed in nature, to not wanting to contribute to trail degradation and soil erosion on busier trails.人们有很多理由想要…

Java入门第三季——Java中的集合框架(中):MapHashMap

1 package com.imooc.collection;2 3 import java.util.HashSet;4 import java.util.Set;5 6 /**7 * 学生类8 * author Administrator9 * 10 */ 11 public class Student { 12 13 public String id; 14 15 public String name; 16 17 public Set<…

【译】 WebSocket 协议第八章——错误处理(Error Handling)

概述 本文为 WebSocket 协议的第八章&#xff0c;本文翻译的主要内容为 WebSocket 错误处理相关内容。 错误处理&#xff08;协议正文&#xff09; 8.1 处理 UTF-8 数据错误 当终端按照 UTF-8 的格式来解析一个字节流&#xff0c;但是发现这个字节流不是 UTF-8 编码&#xff0c…

升级xcode5.1 iOS 6.0后以前的横屏项目 变为了竖屏

升级xcode5.1 iOS 6.0后以前的横屏项目 变为了竖屏&#xff0c;以下为解决办法&#xff1a; 在AppDelegate 的初始化方法 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中 将 [window addSubview: viewCon…

动漫数据推荐系统

Simple, TfidfVectorizer and CountVectorizer recommendation system for beginner.简单的TfidfVectorizer和CountVectorizer推荐系统&#xff0c;适用于初学者。 目标 (The Goal) Recommendation system is widely use in many industries to suggest items to customers. F…

Wait Event SQL*Net more data to client

oracle 官方给的说法是 C.3.152 SQL*Net more data to client The server process is sending more data/messages to the client. The previous operation to the client was also a send. Wait Time: The actual time it took for the send to complete 意味着server process…

1.3求根之牛顿迭代法

目录 目录前言&#xff08;一&#xff09;牛顿迭代法的分析1.定义2.条件3.思想4.误差&#xff08;二&#xff09;代码实现1.算法流程图2.源代码&#xff08;三&#xff09;案例演示1.求解&#xff1a;\(f(x)x^3-x-10\)2.求解&#xff1a;\(f(x)x^2-1150\)3.求解&#xff1a;\(f…

libzbar.a armv7

杨航最近在学IOS&#xfeff;&#xfeff; http://download.csdn.net/download/lzwxyz/5546365 我现在用的是这个&#xff1a;http://www.federicocappelli.net/2012/10/05/zbar-library-for-iphone-5-armv7s/ 点它的HERE开始下载 下载的libzbar.a库&#xff0c;如何查看 …

Alex Hanna博士:Google道德AI小组研究员

Alex Hanna博士是社会学家和研究科学家&#xff0c;致力于Google的机器学习公平性和道德AI。 (Dr. Alex Hanna is a sociologist and research scientist working on machine learning fairness and ethical AI at Google.) Before that, she was an Assistant Professor at th…

三位对我影响最深的老师

我感觉&#xff0c;教过我的老师们&#xff0c;不论他们技术的好坏对我都是有些许影响的。但是让人印象最深的好像只有寥寥几位。 第一位就是小学六年级下册教过我的语文老师。他是临时从一个贫困小学调任过来的&#xff0c;不怎么管班级&#xff0c;班里同学都在背地里说他不会…