在金鑰鏈中新增密碼

每個鑰匙串專案通常表示為 CFDictionary。但是,你可以簡單地在 Objective-C 中使用 NSDictionary 並利用橋接,或者在 Swift 中你可以使用 Dictionary 並明確地轉換為 CFDictionary

你可以使用以下字典構造密碼:

迅速

var dict = [String : AnyObject]()

首先,你需要一個鍵/值對,讓 Keychain 知道這是一個密碼。請注意,因為我們的 dict 鍵是 String,所以我們必須在 Swift 3 中顯式地將任何 CFString 轉換為 String.CFString 不能用作 Swift Dictionary 的鍵,因為它不是 Hashable。

迅速

dict[kSecClass as String] = kSecClassGenericPassword

接下來,我們的密碼可能有一系列屬性來描述它,並幫助我們以後找到它。這是通用密碼的屬性列表

迅速

// The password will only be accessible when the device is unlocked
dict[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlocked
// Label may help you find it later
dict[kSecAttrLabel as String] = "com.me.myapp.myaccountpassword" as CFString
// Username
dict[kSecAttrAccount as String] = "My Name" as CFString
// Service name
dict[kSecAttrService as String] = "MyService" as CFString

最後,我們需要實際的私人資料。一定不要將它留在記憶體中太久。這必須是 CFData

迅速

dict[kSecValueData as String] = "my_password!!".data(using: .utf8) as! CFData

最後,Keychain Services add 函式想知道它應該如何返回新構造的 keychain 項。由於你不應該在記憶體中持久儲存資料,因此以下是你只能返回屬性的方法:

迅速

dict[kSecReturnAttributes as String] = kCFBooleanTrue

現在我們構建了我們的專案。我們來新增它:

迅速

var result: AnyObject?
let status = withUnsafeMutablePointer(to: &result) {
    SecItemAdd(dict as CFDictionary, UnsafeMutablePointer($0))
}
let newAttributes = result as! Dictionary<String, AnyObject>

這將新屬性 dict 放在 result 中。SecItemAdd 接收我們構建的字典,以及指向我們希望結果的指標。然後該函式返回指示成功的 OSStatus 或錯誤程式碼。結果程式碼在此處描述。