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.pswp.cn/news/388262.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388262.shtml
英文地址,請注明出處:http://en.pswp.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;班里同學都在背地里說他不會…