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:


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.


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.


// 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] = "" 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.


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:


dict[kSecReturnAttributes as String] = kCFBooleanTrue

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


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:

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

Table Of Contents