iOS數(shù)據(jù)持久化KeyChain數(shù)據(jù)操作詳解
正文
在我們開發(fā)iOS應(yīng)用的時(shí)候,很多時(shí)候,我們都需要將敏感數(shù)據(jù)(password, accessToken, secretKey等)存儲(chǔ)到本地。對(duì)于初級(jí)程序員來(lái)講,首先映入腦海的可能是使用UserDefaults
。然而,眾所周知,使用UserDefaults
來(lái)存儲(chǔ)敏感信息簡(jiǎn)直是low的不能再low的主意了。因?yàn)槲覀円话愦鎯?chǔ)到UserDefaults
中的數(shù)據(jù)都是未經(jīng)過(guò)編碼處理的,這樣是非常不安全的。
為了能安全的在本地存儲(chǔ)敏感信息,我們應(yīng)當(dāng)使用蘋果提供的KeyChain
服務(wù)。這個(gè)framework已經(jīng)相當(dāng)老了,所以,我們?cè)诤竺骈喿x的時(shí)候,會(huì)覺(jué)得它提供的API并不像當(dāng)下的framework那么快捷。
在本文中,將為你展示如何創(chuàng)建一個(gè)通用的同時(shí)適用于iOS、MacOS的keyChain輔助類,對(duì)數(shù)據(jù)進(jìn)行增刪改查操作。開始吧!??!
保存數(shù)據(jù)到KeyChain
final class KeyChainHelper { static let standard = KeyChainHelper() private init(){} }
我們必須巧妙使用SecItemAdd(_:_:)
方法,這個(gè)方法會(huì)接收一個(gè)CFDictionary
類型的query對(duì)象。
這個(gè)主意是為了創(chuàng)建一個(gè)query對(duì)象,這個(gè)對(duì)象包含了我們想要存儲(chǔ)最主要的數(shù)據(jù)鍵值對(duì)。然后,將query對(duì)象傳入SecItemAdd(_:_:)
方法中來(lái)執(zhí)行保存操作。
func save(_ data: Data, service: String, account: String) { // Create query let query = [ kSecValueData: data, kSecClass: kSecClassGenericPassword, kSecAttrService: service, kSecAttrAccount: account, ] as CFDictionary // Add data in query to keychain let status = SecItemAdd(query, nil) if status != errSecSuccess { // Print out the error print("Error: (status)") } }
回看上述代碼片段,query對(duì)象由4個(gè)鍵值對(duì)組成:
kSecValueData
: 這個(gè)鍵代表著數(shù)據(jù)已經(jīng)被存儲(chǔ)到了keyChain中kSecClass
: 這個(gè)鍵代表著數(shù)據(jù)已經(jīng)被存儲(chǔ)到了keyChain中。我們將它的值設(shè)為了kSecClassGenericPassword
,這代表著我們所保存的數(shù)據(jù)是一個(gè)通用的密碼項(xiàng)kSecAttrService
和kSecAttrAccount
: 當(dāng)kSecClass
被設(shè)置為kSecClassGenericPassword
的時(shí)候,kSecAttrService
和kSecAttrAccount
這兩個(gè)鍵是必須要有的。這兩個(gè)鍵所對(duì)應(yīng)的值將作為所保存數(shù)據(jù)的關(guān)鍵key,換句話說(shuō),我們將使用他們從keyChain中讀取所保存的值。
對(duì)于kSecAttrService
和kSecAttrAccount
所對(duì)應(yīng)的值的定義并沒(méi)有什么難的。推薦使用字符串。例如:如果我們想存儲(chǔ)Facebook的accesToken,我們需要將kSecAttrService
設(shè)置成”access-token“,將kSecAttrAccount
設(shè)置成”facebook“
創(chuàng)建完query對(duì)象之后,我們可以調(diào)用SecItemAdd(_:_:)
方法來(lái)保存數(shù)據(jù)到keyChain。SecItemAdd(_:_:)
方法會(huì)返回一個(gè)OSStatus
來(lái)代表存儲(chǔ)狀態(tài)。如果我們得到的是errSecSuccess
狀態(tài),則意味著數(shù)據(jù)已經(jīng)被成功保存到keyChain中
下面是save(_:service:account:)
方法的使用
let accessToken = "dummy-access-token" let data = Data(accessToken.utf8) KeychainHelper.standard.save(data, service: "access-token", account: "facebook")
keyChain不能在playground中使用,所以,上述代碼必須寫在Controller中。
更新KeyChain中已有的數(shù)據(jù)
現(xiàn)在我們有了save(_:service:account:)
方法,讓我們用相同的kSecAttrService
和kSecAttrAccount
所對(duì)應(yīng)的值來(lái)存儲(chǔ)其他token
let accessToken = "another-dummy-access-token" let data = Data(accessToken.utf8) KeychainHelper.standard.save(data, service: "access-token", account: "facebook")
這時(shí)候,我們就無(wú)法將accessToken保存到keyChain中了。同時(shí),我們會(huì)得到一個(gè)Error: -25299
的報(bào)錯(cuò)。該錯(cuò)誤碼代表的是存儲(chǔ)失敗。因?yàn)槲覀兯褂玫膋eys已經(jīng)存在于keyChain當(dāng)中了。
為了解決這個(gè)問(wèn)題,我們需要檢查這個(gè)錯(cuò)誤碼(相當(dāng)于errSecDuplicateItem
),然后使用SecItemUpdate(_:_:)
方法來(lái)更新keyChain。一起看看并更新我們前述的save(_:service:account:)
方法吧:
func save(_ data: Data, service: String, account: String) { // ... ... // ... ... if status == errSecDuplicateItem { // Item already exist, thus update it. let query = [ kSecAttrService: service, kSecAttrAccount: account, kSecClass: kSecClassGenericPassword, ] as CFDictionary let attributesToUpdate = [kSecValueData: data] as CFDictionary // Update existing item SecItemUpdate(query, attributesToUpdate) } }
跟保存操作相似的是,我們需要先創(chuàng)建一個(gè)query對(duì)象,這個(gè)對(duì)象包含kSecAttrService
和kSecAttrAccount
。但是這次,我們將會(huì)創(chuàng)建另外一個(gè)包含kSecValueData
的字典,并將它傳給SecItemUpdate(_:_:)
方法。
這樣的話,我們就可以讓save(_:service:account:)
方法來(lái)更新keyChain中已有的數(shù)據(jù)了。
從KeyChain中讀取數(shù)據(jù)
從keyChain中讀取數(shù)據(jù)的方式和保存的方式非常相似。我們首先要做的是創(chuàng)建一個(gè)query對(duì)象,然后調(diào)用一個(gè)keyChain方法:
func read(service: String, account: String) -> Data? { let query = [ kSecAttrService: service, kSecAttrAccount: account, kSecClass: kSecClassGenericPassword, kSecReturnData: true ] as CFDictionary var result: AnyObject? SecItemCopyMatching(query, &result) return (result as? Data) }
跟之前一樣,我們需要設(shè)置query對(duì)象的kSecAttrService
and kSecAttrAccount
的值。在這之前,我們需要為query對(duì)象添加一個(gè)新的鍵kSecReturnData
,其值為true
,代表的是我們希望query返回對(duì)應(yīng)項(xiàng)的數(shù)據(jù)。
之后,我們將利用 SecItemCopyMatching(_:_:)
方法并通過(guò)引用傳入 AnyObject
類型的result
對(duì)象。SecItemCopyMatching(_:_:)
方法同樣返回一個(gè)OSStatus類型的值,代表讀取操作狀態(tài)。但是如果讀取失敗了,這里我們不做任何校驗(yàn),并返回nil
讓keyChain支持讀取的操作就這么多了,看一下他是怎么工作的吧
let data = KeychainHelper.standard.read(service: "access-token", account: "facebook")! let accessToken = String(data: data, encoding: .utf8)! print(accessToken)
從KeyChain中刪除數(shù)據(jù)
如果沒(méi)有刪除操作,我們的KeyChainHelper類并不算完成。一起看看下面的代碼片段吧
func delete(service: String, account: String) { let query = [ kSecAttrService: service, kSecAttrAccount: account, kSecClass: kSecClassGenericPassword, ] as CFDictionary // Delete item from keychain SecItemDelete(query) }
如果你全程都在看的話,上述代碼可能對(duì)你來(lái)說(shuō)非常熟悉,那是相當(dāng)?shù)?rdquo;自解釋“了,需要注意的是,這里我們使用了SecItemDelete(_:)
方法來(lái)刪除KeyChain中的數(shù)據(jù)了。
創(chuàng)建一個(gè)通用的KeyChainHelper 類
存儲(chǔ)
func save<T>(_ item: T, service: String, account: String) where T : Codable { do { // Encode as JSON data and save in keychain let data = try JSONEncoder().encode(item) save(data, service: service, account: account) } catch { assertionFailure("Fail to encode item for keychain: (error)") } }
讀取
func read<T>(service: String, account: String, type: T.Type) -> T? where T : Codable { // Read item data from keychain guard let data = read(service: service, account: account) else { return nil } // Decode JSON data to object do { let item = try JSONDecoder().decode(type, from: data) return item } catch { assertionFailure("Fail to decode item for keychain: \(error)") return nil } }
使用
struct Auth: Codable { let accessToken: String let refreshToken: String } // Create an object to save let auth = Auth(accessToken: "dummy-access-token", refreshToken: "dummy-refresh-token") let account = "domain.com" let service = "token" // Save `auth` to keychain KeychainHelper.standard.save(auth, service: service, account: account) // Read `auth` from keychain let result = KeychainHelper.standard.read(service: service, account: account, type: Auth.self)! print(result.accessToken) // Output: "dummy-access-token" print(result.refreshToken) // Output: "dummy-refresh-token"
以上就是iOS數(shù)據(jù)持久化KeyChain的詳細(xì)內(nèi)容,更多關(guān)于iOS數(shù)據(jù)持久化KeyChain的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
IOS 開發(fā)之 UITextField限制字?jǐn)?shù)的方法
這篇文章主要介紹了IOS 開發(fā)之 UITextField限制字?jǐn)?shù)的方法的相關(guān)資料,這里提供實(shí)現(xiàn)限制最大字?jǐn)?shù)的方法,需要的朋友可以參考下2017-08-08IOS開發(fā)過(guò)程中的消息通知--小紅點(diǎn)
本文主要介紹了IOS開發(fā)過(guò)程中的消息通知--小紅點(diǎn)的相關(guān)知識(shí)。大致分為兩種方法:系統(tǒng)方法和自定義方法。下面跟著小編一起來(lái)看下吧2017-04-04iOS實(shí)現(xiàn)“搖一搖”與“掃一掃”功能示例代碼
本篇文章主要介紹了iOS實(shí)現(xiàn)“搖一搖”與“掃一掃”功能示例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01iOS實(shí)現(xiàn)相冊(cè)和網(wǎng)絡(luò)圖片的存取
本篇文章主要介紹了iOS實(shí)現(xiàn)相冊(cè)和網(wǎng)絡(luò)圖片的存取,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-04-04iOS APP中保存圖片到相冊(cè)時(shí)崩潰的解決方法
下面小編就為大家分享一篇iOS APP中保存圖片到相冊(cè)時(shí)崩潰的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-12-12