Adding a Password to the Keychain

suggest change

Every Keychain Item is most often represented as a CFDictionary. You can, however, simply use NSDictionary in Objective-C and take advantage of bridging, or in Swift you may use Dictionary and explicitly cast to CFDictionary.

You could construct a password with the following dictionary:

Swift

var dict = [String : AnyObject]()

First, you need a key/value pair that lets the Keychain know this is a password. Note that because our dict key is a String we must cast any CFString to a String explicitly in Swift 3. CFString may not be used as the key to a Swift Dictionary because it is not Hashable.

Swift

dict[kSecClass as String] = kSecClassGenericPassword

Next, our password may have a series of attributes to describe it and help us find it later. Here’s a list of attributes for generic passwords.

Swift

// 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

Finally, we need our actual private data. Be sure not to keep this around in memory for too long. This must be CFData.

Swift

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

Finally, the Keychain Services add function wants to know how it should return the newly constructed keychain item. Since you shouldn’t be holding on to the data very long in memory, here’s how you could only return the attributes:

Swift

dict[kSecReturnAttributes as String] = kCFBooleanTrue

Now we have constructed our item. Let’s add it:

Swift

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

This places the new attributes dict inside result. SecItemAdd takes in the dictionary we constructed, as well as a pointer to where we would like our result. The function then returns an OSStatus indicating success or an error code. Result codes are described here.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Keychain:
* Adding a Password to the Keychain

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
79 NSURL
87 AWS SDK
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable