更新钥匙串中的密码

像往常一样,我们首先需要一个 CFDictionary 来表示我们想要更新的项目。这必须包含项目的所有旧值,包括旧的私有数据。然后,你需要更改任何属性或数据本身的 CFDictionary

首先,让我们构造一个类键和一个属性列表。这些属性可以缩小我们的搜索范围,但是如果要更改它们,则必须包含任何属性和旧值。

迅速

var dict = [String : AnyObject]()
dict[kSecClass as String] = kSecClassGenericPassword
// Label
dict[kSecAttrLabel as String] = "com.me.myapp.myaccountpassword" as CFString
// Username
dict[kSecAttrAccount as String] = "My Name" as CFString

现在我们必须添加旧数据:

迅速

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

现在让我们创建相同的属性,但不同的密码:

迅速

var newDict = [String : AnyObject]()
newDict[kSecClass as String] = kSecClassGenericPassword
// Label
newDict[kSecAttrLabel as String] = "com.me.myapp.myaccountpassword" as CFString
// Username
newDict[kSecAttrAccount as String] = "My Name" as CFString
// New password
newDict[kSecValueData as String] = "new_password!!".data(using: .utf8) as! CFData

现在,我们将其传递给 Keychain Services:

迅速

let status = SecItemUpdate(dict as CFDictionary, newDict as CFDictionary)

SecItemUpdate 返回状态代码。结果在这里描述。