write a string to the keychain in swift

To store a string securely in the Keychain, you can use the Keychain Services API provided by Apple. Here's an example function that takes a string and a key name as input, and stores the string in the Keychain using the default kSecClassGenericPassword class:

main.swift
import Security

func storeStringInKeychain(key: String, value: String) -> OSStatus {
    guard let data = value.data(using: String.Encoding.utf8) else {
        return errSecInvalidData
    }

    let query = [
        kSecClass as String: kSecClassGenericPassword as String,
        kSecAttrAccount as String: key,
        kSecValueData as String: data
    ] as [String: Any]

    SecItemDelete(query as CFDictionary)
    let status = SecItemAdd(query as CFDictionary, nil)

    return status
}
497 chars
19 lines

In this function, we first convert the input string into a Data object using the UTF-8 encoding. Then we create a dictionary with the Keychain attributes that we want to set:

  • kSecClass: The class of the Keychain item. In this case, we're using the kSecClassGenericPassword class, which allows us to store arbitrary data as a password item.
  • kSecAttrAccount: The name of the Keychain item, which we set to the input key.
  • kSecValueData: The data to be stored in the Keychain, which we set to the data object.

We also call SecItemDelete to delete any existing Keychain item with the specified key, to avoid duplicates. Finally, we call SecItemAdd to add the new item to the Keychain.

To read a string from the Keychain, you can use the SecItemCopyMatching function with a similar query dictionary.

gistlibby LogSnag