Mac Developer Library

Developer

Security Framework Reference Keychain Services Reference

Options
Deployment Target:

On This Page
Language:

Keychain Services Reference

Keychain Services is a programming interface that enables you to find, add, modify, and delete keychain items.

If you want to look at some code that uses this API, you can find the source code for the security command-line tool in the SecurityTool project on Apple's Open Source website.

Functions

For this interface, keychain items are found or defined by a CFDictionary of key-value pairs. Each key in the dictionary identifies one attribute of the keychain item, or a search option. For example, you can use the kSecClass key to specify that the keychain item is an Internet password, that it has a specific creation date, that it is for the HTTPS protocol, and that only the first match found should be returned. The keys that can be used for this purpose and the possible values for each key are listed in the Keychain Services Constants section.

See the discussion section of the SecItemCopyMatching function for information about how to construct a keychain-item search dictionary.

  • Returns one or more keychain items that match a search query, or copies attributes of specific keychain items.

    Declaration

    Swift

    func SecItemCopyMatching(_ query: CFDictionary, _ result: UnsafeMutablePointer<AnyObject?>) -> OSStatus

    Objective-C

    OSStatus SecItemCopyMatching ( CFDictionaryRef query, CFTypeRef _Nullable *result );

    Parameters

    query

    A dictionary containing an item class specification (Keychain Item Class Keys and Values) and optional attributes for controlling the search. See Keychain Services Constants for a description of currently defined search attributes.

    result

    On return, a reference to the found items. The exact type of the result is based on the search attributes supplied in the query, as discussed below.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    You specify attributes defining a search by adding key-value pairs to the query dictionary.

    A typical query consists of:

    Return types (Search Results Constants) are specified as follows:

    • To obtain a reference (of type CFDataRef) to the data of a matching item, specify kSecReturnData with a value of kCFBooleanTrue.

    • To obtain a dictionary (of type CFDictionaryRef) containing the attributes of a matching item, specify kSecReturnAttributes with a value of kCFBooleanTrue.

    • To obtain a reference (of type SecKeychainItemRef, SecKeyRef, SecCertificateRef, or SecIdentityRef) to a matching item, specify kSecReturnRef with a value of kCFBooleanTrue.

    • To obtain a persistent reference (of type CFDataRef) to a matching item, specify kSecReturnPersistentRef with a value of kCFBooleanTrue. Note that unlike normal references, a persistent reference may be stored on disk or passed between processes.

    • If more than one return type is specified (for example, kSecReturnRef and kSecReturnAttributes), the results are returned as a dictionary (that is, an object of type CFDictionaryRef) containing all the requested data.

    By default, this function returns only the first match found. To obtain more than one matching item at a time, specify the search key kSecMatchLimit with a value greater than 1. The result will be an object of type CFArrayRef containing up to that number of matching items.

    By default, this function searches for items in the keychain. To instead provide your own set of items to be filtered by this search query, specify the search key kSecMatchItemList and provide as its value a CFArrayRef object containing items of type SecKeychainItemRef, SecKeyRef, SecCertificateRef, or SecIdentityRef. The objects in the provided array must all be of the same type.

    To limit a keychain search to a particular keychain or keychains, specify the search key kSecMatchSearchList and provide as its value a CFArrayRef object containing items of type SecKeychainRef items.

    To convert from persistent item references to normal item references, specify the search key kSecMatchItemList with a value that consists of an object of type CFArrayRef referencing an array containing one or more elements of type CFDataRef (the persistent references), and a return-type key of kSecReturnRef whose value is kCFBooleanTrue. The objects in the provided array must all be of the same type.

    When you use Xcode to create an application, Xcode adds an application-identifier entitlement to the application bundle. Keychain Services uses this entitlement to grant the application access to its own keychain items. You can also add a keychain-access-groups entitlement to the application and, in the entitlement property list file, specify an array of keychain access groups to which the application belongs. The property list file can have any name you like (for example, keychain-access-groups.plist). The Xcode build variable CODE_SIGN_ENTITLEMENTS should contain the SRCROOT relative path to the entitlement property list file. The property list file itself should be a dictionary with a top-level key called keychain-access-groups whose value is an array of strings. When you call the SecItemAdd function to add an item to the keychain, you can specify the access group to which that item should belong. By default, the SecItemCopyMatching function searches all the access groups to which the application belongs. However, you can add the kSecAttrAccessGroup key to the search dictionary to specify which access group to search for keychain items.

    Availability

    Available in OS X v10.6 and later.

  • Adds one or more items to a keychain.

    Declaration

    Swift

    func SecItemAdd(_ attributes: CFDictionary, _ result: UnsafeMutablePointer<AnyObject?>) -> OSStatus

    Objective-C

    OSStatus SecItemAdd ( CFDictionaryRef attributes, CFTypeRef _Nullable *result );

    Parameters

    attributes

    A dictionary containing an item class key-value pair (Keychain Item Class Keys and Values) and optional attribute key-value pairs (Attribute Item Keys and Values) specifying the item's attribute values.

    result

    On return, a reference to the newly added items. The exact type of the result is based on the values supplied in attributes, as discussed below. Pass NULL if this result is not required.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    You specify attributes defining an item by adding key-value pairs to the attributes dictionary. To add multiple items to a keychain at once use the kSecUseItemList key (see section Item List Key) with an array of items as its value. This is only supported for non-password items.

    If you want the new keychain item to be shared among multiple applications, include the kSecAttrAccessGroup key in the attributes dictionary. The value of this key must be the name of a keychain access group to which all of the programs that will share this item belong.

    When you use Xcode to create an application, Xcode adds an application-identifier entitlement to the application bundle. Keychain Services uses this entitlement to grant the application access to its own keychain items. You can also add a keychain-access-groups entitlement to the application and, in the entitlement property list file, specify an array of keychain access groups to which the application belongs. The property list file can have any name you like (for example, keychain-access-groups.plist). The Xcode build variable CODE_SIGN_ENTITLEMENTS should contain the SRCROOT relative path to the entitlement property list file. The property list file itself should be a dictionary with a top-level key called keychain-access-groups whose value is an array of strings. If you add such a property-list file to the application bundle, then the access group corresponding to the application-identifier entitlement is treated as the last element in the access groups array. If you do not include the kSecAttrAccessGroup key in the attributes dictionary when you call the SecItemAdd function to add an item to the keychain, the function uses the first access group in the array by default. If there is no kSecAttrAccessGroup key in the attributes dictionary and there is no keychain-access-groups entitlement in the application bundle, then the access group of a newly created item is the value of the application-identifier entitlement.

    For example, a development group in Apple might have the ID:

    659823F3DC53.com.apple

    and the application identifiers of their two applications might be:

    659823F3DC53.com.apple.oneappleapp and

    659823F3DC53.com.apple.twoappleapp

    If both applications add a keychain-access-groups entitlement with one value in the array of access groups:

    659823F3DC53.com.apple.netaccount

    then both applications would add new keychain items to the 659823F3DC53.com.apple.netaccount access group by default and both applications would have access to keychain items in that group. In addition, each application would still have access to its own private keychain items: OneAppleApp would have access to items in keychain access group 659823F3DC53.com.apple.oneappleapp and TwoAppleApp would have access to items in 659823F3DC53.com.apple.twoappleapp.

    Return types (Search Results Constants) are specified as follows:

    • To obtain the data of the added item as an object of type CFDataRef, specify the return type key kSecReturnData with a value of kCFBooleanTrue.

    • To obtain all the attributes of the added item as objects of type CFDictionaryRef, specify kSecReturnAttributes with a value of kCFBooleanTrue.

    • To obtain a reference to the added item of type SecKeychainItemRef, SecKeyRef, SecCertificateRef, or SecIdentityRef), specify kSecReturnRef with a value of kCFBooleanTrue. This is the default behavior if a return type is not explicitly specified.

    • To obtain a persistent reference to the added item (an object of type CFDataRef), specify kSecReturnPersistentRef with a value of kCFBooleanTrue. Note that unlike normal references, a persistent reference may be stored on disk or passed between processes.

    • If more than one of these return types is specified, the result is returned as an object of type CFDictionaryRef containing all the requested data.

    Availability

    Available in OS X v10.6 and later.

  • Modifies items that match a search query.

    Declaration

    Swift

    func SecItemUpdate(_ query: CFDictionary, _ attributesToUpdate: CFDictionary) -> OSStatus

    Objective-C

    OSStatus SecItemUpdate ( CFDictionaryRef query, CFDictionaryRef attributesToUpdate );

    Parameters

    query

    A dictionary containing an item class specification and optional attributes for controlling the search. Specify the items whose values you wish to change. See Search Keys for a description of currently defined search attributes.

    attributesToUpdate

    A dictionary containing the attributes whose values should be changed, along with the new values. Only real keychain attributes are permitted in this dictionary (no "meta" attributes are allowed.) See Attribute Item Keys and Values for a description of currently defined value attributes.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    See the discussion section of the SecItemCopyMatching function for information about how to construct a search dictionary.

    Availability

    Available in OS X v10.6 and later.

  • Deletes items that match a search query.

    Declaration

    Swift

    func SecItemDelete(_ query: CFDictionary) -> OSStatus

    Objective-C

    OSStatus SecItemDelete ( CFDictionaryRef query );

    Parameters

    query

    A dictionary containing an item class specification and optional attributes for controlling the search. See Search Keys for a description of currently defined search attributes.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    See the discussion section of the SecItemCopyMatching function for information about how to construct a search dictionary.

    By default, this function deletes all items matching the specified query. You can change this behavior by specifying a key, as follows:

    • To delete an item identified by a transient reference, specify the kSecMatchItemList search key with a reference returned by using the kSecReturnRef return type key in a previous call to the SecItemCopyMatching or SecItemAdd functions.

    • To delete an item identified by a persistent reference, specify the kSecMatchItemList search key with a persistent reference returned by using the kSecReturnPersistentRef return type key to the SecItemCopyMatching or SecItemAdd functions.

    • If more than one of these return keys is specified, the behavior is undefined.

    Availability

    Available in OS X v10.6 and later.

  • Returns a string explaining the meaning of a security result code.

    Declaration

    Swift

    func SecCopyErrorMessageString(_ status: OSStatus, _ reserved: UnsafeMutablePointer<Void>) -> CFString?

    Objective-C

    CFStringRef SecCopyErrorMessageString ( OSStatus status, void *reserved );

    Parameters

    status

    A result code of type OSStatus or CSSM_RETURN, returned by a security or CSSM function.

    reserved

    Reserved for future use. Pass NULL for this parameter.

    Return Value

    A human-readable string describing the result, or NULL if no string is available for the specified result code. You must call the CFRelease function to release this object when you are finished using it.

    Availability

    Available in OS X v10.3 and later.

  • Determines the version of Keychain Services installed on the user’s system.

    Declaration

    Swift

    func SecKeychainGetVersion(_ returnVers: UnsafeMutablePointer<UInt32>) -> OSStatus

    Objective-C

    OSStatus SecKeychainGetVersion ( UInt32 *returnVers );

    Parameters

    returnVers

    On return, a pointer to the version number of Keychain Services installed on the current system. See Keychain Settings Version for a list of values.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Your application can call the SecKeychainGetVersion function to find out which version of Keychain Services is installed on the user’s system.

    Availability

    Available in OS X v10.2 and later.

  • Returns the unique identifier of the opaque type to which a SecKeychainRef object belongs.

    Declaration

    Swift

    func SecKeychainGetTypeID() -> CFTypeID

    Objective-C

    CFTypeID SecKeychainGetTypeID ( void );

    Return Value

    A value that identifies the opaque type of a SecKeychainRef object.

    Discussion

    This function returns a value that uniquely identifies the opaque type of a SecKeychainRef object. You can compare this value to the CFTypeID identifier obtained by calling the CFGetTypeID function on a specific object. These values might change from release to release or platform to platform.

    Availability

    Available in OS X v10.2 and later.

  • Returns the unique identifier of the opaque type to which a SecKeychainItemRef object belongs.

    Declaration

    Swift

    func SecKeychainItemGetTypeID() -> CFTypeID

    Objective-C

    CFTypeID SecKeychainItemGetTypeID ( void );

    Return Value

    A value that identifies the opaque type of a SecKeychainItemRef object.

    Discussion

    This function returns a value that uniquely identifies the opaque type of a SecKeychainItemRef object. You can compare this value to the CFTypeID identifier obtained by calling the CFGetTypeID function on a specific object. These values might change from release to release or platform to platform.

    Availability

    Available in OS X v10.2 and later.

  • Returns the unique identifier of the opaque type to which a SecKeychainSearchRef object belongs.

    Declaration

    Objective-C

    CFTypeID SecKeychainSearchGetTypeID ( void );

    Return Value

    A value that identifies the opaque type of a SecKeychainSearchRef object.

    Discussion

    This function returns a value that uniquely identifies the opaque type of a SecKeychainSearchRef object. You can compare this value to the CFTypeID identifier obtained by calling the CFGetTypeID function on a specific object. These values might change from release to release or platform to platform.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Returns the unique identifier of the opaque type to which a SecAccessRef object belongs.

    Declaration

    Swift

    func SecAccessGetTypeID() -> CFTypeID

    Objective-C

    CFTypeID SecAccessGetTypeID ( void );

    Return Value

    A value that identifies the opaque type of a SecAccessRef object.

    Discussion

    This function returns a value that uniquely identifies the opaque type of a SecAccessRef object. You can compare this value to the CFTypeID identifier obtained by calling the CFGetTypeID function on a specific object. These values might change from release to release or platform to platform.

    Availability

    Available in OS X v10.2 and later.

  • Returns the unique identifier of the opaque type to which a SecACLRef object belongs.

    Declaration

    Swift

    func SecACLGetTypeID() -> CFTypeID

    Objective-C

    CFTypeID SecACLGetTypeID ( void );

    Return Value

    A value that identifies the opaque type of a SecACLRef object.

    Discussion

    This function returns a value that uniquely identifies the opaque type of a SecACLRef object. You can compare this value to the CFTypeID identifier obtained by calling the CFGetTypeID function on a specific object. These values might change from release to release or platform to platform.

    Availability

    Available in OS X v10.3 and later.

  • Returns the unique identifier of the opaque type to which a SecTrustedApplication object belongs.

    Declaration

    Swift

    func SecTrustedApplicationGetTypeID() -> CFTypeID

    Objective-C

    CFTypeID SecTrustedApplicationGetTypeID ( void );

    Return Value

    A value that identifies the opaque type of a SecTrustedApplicationRef object.

    Discussion

    This function returns a value that uniquely identifies the opaque type of a SecTrustedApplicationRef object. You can compare this value to the CFTypeID identifier obtained by calling the CFGetTypeID function on a specific object. These values might change from release to release or platform to platform.

    Availability

    Available in OS X v10.2 and later.

  • Creates an empty keychain.

    Declaration

    Swift

    func SecKeychainCreate(_ pathName: UnsafePointer<Int8>, _ passwordLength: UInt32, _ password: UnsafePointer<Void>, _ promptUser: Bool, _ initialAccess: SecAccess?, _ keychain: UnsafeMutablePointer<SecKeychain?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainCreate ( const char *pathName, UInt32 passwordLength, const void *password, Boolean promptUser, SecAccessRef initialAccess, SecKeychainRef _Nullable *keychain );

    Parameters

    pathName

    A constant character string representing the POSIX path indicating where to store the keychain.

    passwordLength

    An unsigned 32-bit integer representing the length of the buffer pointed to by password. Pass 0 if the value of password is NULL and the value of promptUser is TRUE.

    password

    A pointer to the buffer containing the password which is used to protect the new keychain. The password must be in canonical UTF-8 encoding. Pass NULL if the value of passwordLength is 0 and the value of promptUser is TRUE.

    promptUser

    A Boolean value representing whether to display a password dialog to the user. Set this value to TRUE to display a password dialog or FALSE otherwise. If you pass TRUE, any values passed for passwordLength and password are ignored, and a dialog for the user to enter a password is presented.

    initialAccess

    An access object indicating the initial access rights for the keychain. A keychain’s access rights determine which applications have permission to use the keychain. You may pass NULL for the standard access rights.

    keychain

    On return, a pointer to a keychain object. You must call the CFRelease function to release this object when you are finished using it. Pass NULL if you do not need the pointer to the keychain object returned.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function creates an empty keychain. The keychain, password, and initialAccess parameters are optional. If user interaction to create a keychain is posted, the newly-created keychain is automatically unlocked after creation.

    The system ensures that a default keychain is created for the user at login, thus, in most cases, you do not need to call this function yourself. Users can create additional keychains, or change the default, by using the Keychain Access application. However, a missing default keychain is not recreated automatically, and you may receive an errSecNoDefaultKeychain error from other functions if a default keychain does not exist. In that case, you can use this function followed by SecKeychainSetDefault, to create a new default keychain. You can also call this function to create a private temporary keychain for your application’s use, in cases where no user interaction can occur.

    Availability

    Available in OS X v10.2 and later.

  • Deletes one or more keychains from the default keychain search list, and removes the keychain itself if it is a file.

    Declaration

    Swift

    func SecKeychainDelete(_ keychainOrArray: SecKeychain?) -> OSStatus

    Objective-C

    OSStatus SecKeychainDelete ( SecKeychainRef keychainOrArray );

    Parameters

    keychainOrArray

    A single keychain object or a reference to an array of keychains you wish to delete. To delete more than one keychain, create a CFArray of keychain references (type SecKeychainRef) and pass a reference to the array.

    In OS X v10.3 and later, passing NULL to this parameter returns an errSecInvalidKeychain error code. In OS X v10.2, this parameter was named keychain and only took a single keychain object. Passing NULL to this parameter deleted the user’s default keychain.

    Return Value

    A result code. See Keychain Services Result Codes. The result code errSecInvalidKeychain is returned if the specified keychain is invalid or if the value of the keychainOrArray parameter is invalid (NULL). Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    The keychain may be a file stored locally, a smart card, or retrieved from a network server using non-file-based database protocols. This function deletes the keychain only if it is a local file.

    This function does not release the memory used by the keychain object; you must call the CFRelease function to release each keychain object when you are finished with it.

    Availability

    Available in OS X v10.2 and later.

  • Opens a keychain.

    Declaration

    Swift

    func SecKeychainOpen(_ pathName: UnsafePointer<Int8>, _ keychain: UnsafeMutablePointer<SecKeychain?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainOpen ( const char *pathName, SecKeychainRef _Nullable *keychain );

    Parameters

    pathName

    A constant character string representing the POSIX path to the keychain to open.

    keychain

    On return, a pointer to the keychain object. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    You may use this function to retrieve a pointer to a keychain object given the path of the keychain. You do not need to close the keychain, but you should release the memory that the pointer occupies when you are finished with it.

    Availability

    Available in OS X v10.2 and later.

  • Sets the default keychain.

    Declaration

    Swift

    func SecKeychainSetDefault(_ keychain: SecKeychain?) -> OSStatus

    Objective-C

    OSStatus SecKeychainSetDefault ( SecKeychainRef keychain );

    Parameters

    keychain

    A reference to the keychain you wish to make the default.

    Return Value

    A result code. See Keychain Services Result Codes. The result code errSecNoSuchKeychain indicates that the specified keychain could not be found. The result code errSecInvalidKeychain indicates that the specified keychain is invalid. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    In most cases, your application should not need to set the default keychain, because this is a choice normally made by the user. You may call this function to change where a password or other keychain items are added, but since this is a user choice, you should set the default keychain back to the user specified keychain when you are done.

    Availability

    Available in OS X v10.2 and later.

  • Retrieves a pointer to the default keychain.

    Declaration

    Swift

    func SecKeychainCopyDefault(_ keychain: UnsafeMutablePointer<SecKeychain?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainCopyDefault ( SecKeychainRef _Nullable *keychain );

    Parameters

    keychain

    On return, a pointer to the default keychain object. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. The result code errSecNoDefaultKeychain indicates that there is no default keychain. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.2 and later.

  • Retrieves status information of a keychain.

    Declaration

    Swift

    func SecKeychainGetStatus(_ keychain: SecKeychain?, _ keychainStatus: UnsafeMutablePointer<SecKeychainStatus>) -> OSStatus

    Objective-C

    OSStatus SecKeychainGetStatus ( SecKeychainRef keychain, SecKeychainStatus *keychainStatus );

    Parameters

    keychain

    A keychain object of the keychain whose status you wish to determine for the user session. Pass NULL to obtain the status of the default keychain.

    keychainStatus

    On return, a pointer to the status of the specified keychain. See Keychain Status Masks for valid status constants.

    Return Value

    A result code. See Keychain Services Result Codes. The result code errSecNoSuchKeychain indicates that the specified keychain could not be found. The result code errSecInvalidKeychain indicates that the specified keychain is invalid. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function retrieves the status of a specified keychain. You can use this function to determine if the keychain is unlocked, readable, or writable. Note that the lock status of a keychain can change at any time due to user or system activity. Because the system automatically prompts the user to unlock a keychain when necessary, you do not usually have to worry about the lock status of a keychain. If you do need to track the lock status of a keychain, use the SecKeychainAddCallback function to register for keychain notifications.

    Availability

    Available in OS X v10.2 and later.

  • Determines the path of a keychain.

    Declaration

    Swift

    func SecKeychainGetPath(_ keychain: SecKeychain?, _ ioPathLength: UnsafeMutablePointer<UInt32>, _ pathName: UnsafeMutablePointer<Int8>) -> OSStatus

    Objective-C

    OSStatus SecKeychainGetPath ( SecKeychainRef keychain, UInt32 *ioPathLength, char *pathName );

    Parameters

    keychain

    A reference to a keychain whose path you wish to obtain.

    ioPathLength

    On entry, a pointer to a variable containing the length (in bytes) of the buffer specified by pathName.

    On return, the string length of pathName, not including the null termination.

    pathName

    On entry, a pointer to a buffer that you have allocated. On return, the buffer contains POSIX path of the keychain as a null-terminated UTF-8 encoded string. The function returns errSecBufferTooSmall if the provided buffer is too small to hold the string with the null terminator byte.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.2 and later.

  • Changes the settings of a keychain.

    Declaration

    Swift

    func SecKeychainSetSettings(_ keychain: SecKeychain?, _ newSettings: UnsafePointer<SecKeychainSettings>) -> OSStatus

    Objective-C

    OSStatus SecKeychainSetSettings ( SecKeychainRef keychain, const SecKeychainSettings *newSettings );

    Parameters

    keychain

    A reference to a keychain whose settings you wish to change. Pass NULL to change the settings of the default keychain.

    newSettings

    A pointer to a keychain settings structure that defines whether the keychain locks when sleeping, or locks after a set time period of inactivity.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.2 and later.

  • Obtains a keychain’s settings.

    Declaration

    Swift

    func SecKeychainCopySettings(_ keychain: SecKeychain?, _ outSettings: UnsafeMutablePointer<SecKeychainSettings>) -> OSStatus

    Objective-C

    OSStatus SecKeychainCopySettings ( SecKeychainRef keychain, SecKeychainSettings *outSettings );

    Parameters

    keychain

    A reference to the keychain from which to copy its settings.

    outSettings

    On return, a pointer to a keychain settings structure. Since this structure is versioned, you must allocate the memory for it and fill in the version of the structure before passing it to the function.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.2 and later.

  • Locks a keychain.

    Declaration

    Swift

    func SecKeychainLock(_ keychain: SecKeychain?) -> OSStatus

    Objective-C

    OSStatus SecKeychainLock ( SecKeychainRef keychain );

    Parameters

    keychain

    A reference to the keychain to lock. Pass NULL to lock the default keychain.

    Return Value

    A result code. See Keychain Services Result Codes.The result code errSecNoSuchKeychain indicates that specified keychain could not be found. The result code errSecInvalidKeychain indicates that the specified keychain is invalid. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Your application should not call this function unless you are responding to a user’s request to lock a keychain. In general, you should leave the keychain unlocked so that the user does not have to unlock it again in another application.

    Availability

    Available in OS X v10.2 and later.

  • Locks all keychains belonging to the current user.

    Declaration

    Swift

    func SecKeychainLockAll() -> OSStatus

    Objective-C

    OSStatus SecKeychainLockAll ( void );

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Your application should not call this function unless you are responding to a user’s request to lock a keychain. In general, you should leave the keychain unlocked so that the user does not have to unlock it again in another application.

    Availability

    Available in OS X v10.2 and later.

  • Unlocks a keychain.

    Declaration

    Swift

    func SecKeychainUnlock(_ keychain: SecKeychain?, _ passwordLength: UInt32, _ password: UnsafePointer<Void>, _ usePassword: Bool) -> OSStatus

    Objective-C

    OSStatus SecKeychainUnlock ( SecKeychainRef keychain, UInt32 passwordLength, const void *password, Boolean usePassword );

    Parameters

    keychain

    A reference to the keychain to unlock. Pass NULL to specify the default keychain. If you pass a locked keychain, this function displays the Unlock Keychain dialog box if you have not provided a password. If the specified keychain is currently unlocked, the Unlock Keychain dialog box is not displayed and this function returns noErr. You must call the CFRelease function to release this object when you are finished using it.

    passwordLength

    An unsigned 32-bit integer representing the length of the password buffer.

    password

    A buffer containing the password for the keychain. Pass NULL if the user password is unknown. In this case, this function displays the Unlock Keychain dialog to prompt the user for the keychain password.

    usePassword

    A Boolean value indicating whether the password parameter is used. You should pass TRUE if you are passing a password or FALSE if it is to be ignored.

    Return Value

    A result code. See Keychain Services Result Codes. The result code userCanceledErr indicates that the user pressed the Cancel button in the Unlock Keychain dialog box. The result code errSecAuthFailed indicates that authentication failed because of too many unsuccessful retries. The result code errSecInteractionRequired indicates that user interaction is required to unlock the keychain. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    In most cases, your application does not need to call this function directly, since most Keychain Services functions that require an unlocked keychain do so for you. If your application needs to verify that a keychain is unlocked, call the function SecKeychainGetStatus.

    Availability

    Available in OS X v10.2 and later.

  • Enables or disables the user interface for Keychain Services functions that automatically display a user interface.

    Declaration

    Swift

    func SecKeychainSetUserInteractionAllowed(_ state: Bool) -> OSStatus

    Objective-C

    OSStatus SecKeychainSetUserInteractionAllowed ( Boolean state );

    Parameters

    state

    A flag that indicates whether the Keychain Services will display a user interface. If you pass TRUE, user interaction is allowed. This is the default value. If FALSE, Keychain Services functions that normally display a user interface will instead return an error.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Certain Keychain Services functions that require the presence of a keychain automatically display a Keychain Not Found dialog if there is none. Functions that require the keychain to be unlocked automatically display the Unlock Keychain dialog. The SecKeychainSetUserInteractionAllowed function enables you to control whether these functions display a user interface. By default, user interaction is permitted.

    If you are writing an application that must run unattended on a server, you may wish to disable the user interface so that any subsequent keychain calls that normally bring up the unlock UI will instead return immediately with an errSecInteractionRequired result). In this case you must programmatically create a keychain or unlock the keychain when necessary.

    Special Considerations

    If you disable user interaction before calling a Keychain Services function, be sure to reenable it when you are finished. Failure to reenable user interaction will affect other clients of the Keychain Services.

    Availability

    Available in OS X v10.2 and later.

  • Indicates whether Keychain Services functions that normally display a user interaction are allowed to do so.

    Declaration

    Swift

    func SecKeychainGetUserInteractionAllowed(_ state: UnsafeMutablePointer<DarwinBoolean>) -> OSStatus

    Objective-C

    OSStatus SecKeychainGetUserInteractionAllowed ( Boolean *state );

    Parameters

    state

    On return, a Boolean value indicating whether user interaction is permitted. If true, user interaction is allowed, and Keychain Services functions that display a user interface can do so as appropriate.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.2 and later.

  • Sets the application access for a keychain.

    Declaration

    Swift

    func SecKeychainSetAccess(_ keychain: SecKeychain?, _ access: SecAccess) -> OSStatus

    Objective-C

    OSStatus SecKeychainSetAccess ( SecKeychainRef keychain, SecAccessRef access );

    Parameters

    keychain

    A reference to the keychain for which to set the access. Pass NULL to specify the default keychain.

    access

    An access object of type SecAccessRef containing access control lists for the keychain. See Creating an Access Object for instructions on creating an access object.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    In addition to the ACLs for individual keychain items, the keychain itself has ACLs. However, they are currently unused and this function is unimplemented.

    Special Considerations

    Although this function is available in OS X v10.2 and later, it is unimplemented and returns an errSecUnimplemented error code if called.

    Availability

    Available in OS X v10.2 and later.

  • Retrieves the application access of a keychain.

    Declaration

    Swift

    func SecKeychainCopyAccess(_ keychain: SecKeychain?, _ access: UnsafeMutablePointer<SecAccess?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainCopyAccess ( SecKeychainRef keychain, SecAccessRef _Nullable *access );

    Parameters

    keychain

    A reference to the keychain from which to copy the access object. Pass NULL to specify the default keychain.

    access

    A pointer to an access object. On return, this points to the access object of the specified keychain. See Managing Access Objects for information on manipulating access objects.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Special Considerations

    Although this function is available in OS X v10.2, it was unimplemented before OS X v10.3 and returned an errSecUnimplemented error code if called.

    Availability

    Available in OS X v10.2 and later.

  • Adds a new Internet password to a keychain.

    Declaration

    Swift

    func SecKeychainAddInternetPassword(_ keychain: SecKeychain?, _ serverNameLength: UInt32, _ serverName: UnsafePointer<Int8>, _ securityDomainLength: UInt32, _ securityDomain: UnsafePointer<Int8>, _ accountNameLength: UInt32, _ accountName: UnsafePointer<Int8>, _ pathLength: UInt32, _ path: UnsafePointer<Int8>, _ port: UInt16, _ protocol: SecProtocolType, _ authenticationType: SecAuthenticationType, _ passwordLength: UInt32, _ passwordData: UnsafePointer<Void>, _ itemRef: UnsafeMutablePointer<SecKeychainItem?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainAddInternetPassword ( SecKeychainRef keychain, UInt32 serverNameLength, const char *serverName, UInt32 securityDomainLength, const char *securityDomain, UInt32 accountNameLength, const char *accountName, UInt32 pathLength, const char *path, UInt16 port, SecProtocolType protocol, SecAuthenticationType authenticationType, UInt32 passwordLength, const void *passwordData, SecKeychainItemRef _Nullable *itemRef );

    Parameters

    keychain

    A reference to the keychain in which to store an Internet password. Pass NULL to specify the user’s default keychain.

    serverNameLength

    The length of the serverName character string.

    serverName

    A UTF-8 encoded character string representing the server name.

    securityDomainLength

    The length of the securityDomain character string.

    securityDomain

    A UTF-8 encoded character string representing the security domain. This parameter is optional. Pass NULL if the protocol does not require it.

    accountNameLength

    The length of the accountName character string.

    accountName

    A UTF-8 encoded character string representing the account name.

    pathLength

    The length of the path character string.

    path

    A UTF-8 encoded character string representing the path.

    port

    The TCP/IP port number. If no specific port number is associated with this password, pass 0.

    protocol

    The protocol associated with this password. See Keychain Protocol Type Constants for a description of possible values.

    authenticationType

    The authentication scheme used. See Keychain Authentication Type Constants for a description of possible values. Pass the constant kSecAuthenticationTypeDefault, to specify the default authentication scheme.

    passwordLength

    The length of the passwordData buffer.

    passwordData

    A pointer to a buffer containing the password data to be stored in the keychain.

    itemRef

    On return, a pointer to a reference to the new keychain item. Pass NULL if you don’t want to obtain this object. You must allocate the memory for this pointer. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. The result code errSecNoDefaultKeychain indicates that no default keychain could be found. The result code errSecDuplicateItem indicates that you tried to add a password that already exists in the keychain. The result code errSecDataTooLarge indicates that you tried to add more data than is allowed for a structure of this type. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function adds a new Internet server password to the specified keychain. Required parameters to identify the password are serverName and accountName (you cannot pass NULL for both parameters). In addition, some protocols may require an optional securityDomain when authentication is requested. This function optionally returns a reference to the newly added item.

    This function sets the initial access rights for the new keychain item so that the application creating the item is given trusted access.

    This function automatically calls the function SecKeychainUnlock to display the Unlock Keychain dialog box if the keychain is currently locked.

    Availability

    Available in OS X v10.2 and later.

  • Finds the first Internet password based on the attributes passed.

    Declaration

    Swift

    func SecKeychainFindInternetPassword(_ keychainOrArray: AnyObject?, _ serverNameLength: UInt32, _ serverName: UnsafePointer<Int8>, _ securityDomainLength: UInt32, _ securityDomain: UnsafePointer<Int8>, _ accountNameLength: UInt32, _ accountName: UnsafePointer<Int8>, _ pathLength: UInt32, _ path: UnsafePointer<Int8>, _ port: UInt16, _ protocol: SecProtocolType, _ authenticationType: SecAuthenticationType, _ passwordLength: UnsafeMutablePointer<UInt32>, _ passwordData: UnsafeMutablePointer<UnsafeMutablePointer<Void>>, _ itemRef: UnsafeMutablePointer<SecKeychainItem?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainFindInternetPassword ( CFTypeRef keychainOrArray, UInt32 serverNameLength, const char *serverName, UInt32 securityDomainLength, const char *securityDomain, UInt32 accountNameLength, const char *accountName, UInt32 pathLength, const char *path, UInt16 port, SecProtocolType protocol, SecAuthenticationType authenticationType, UInt32 *passwordLength, void * _Nullable *passwordData, SecKeychainItemRef _Nullable *itemRef );

    Parameters

    keychainOrArray

    A reference to an array of keychains to search, a single keychain or NULL to search the user’s default keychain search list.

    serverNameLength

    The length of the serverName character string.

    serverName

    A UTF-8 encoded character string representing the server name.

    securityDomainLength

    The length of the securityDomain character string.

    securityDomain

    A UTF-8 encoded character string representing the security domain. This parameter is optional, as not all protocols require it. Pass NULL if it is not required.

    accountNameLength

    The length of the accountName character string.

    accountName

    A UTF-8 encoded character string representing the account name.

    pathLength

    The length of the path character string.

    path

    A UTF-8 encoded character string representing the path.

    port

    The TCP/IP port number. Pass 0 to ignore the port number.

    protocol

    The protocol associated with this password. See Keychain Protocol Type Constants for a description of possible values.

    authenticationType

    The authentication scheme used. See Keychain Authentication Type Constants for a description of possible values. Pass the constant kSecAuthenticationTypeDefault, to specify the default authentication scheme.

    passwordLength

    On return, the length of the buffer pointed to by passwordData.

    passwordData

    On return, a pointer to a buffer containing the password data. Pass NULL if you want to obtain the item object but not the password data. In this case, you must also pass NULL in the passwordLength parameter. You should use the SecKeychainItemFreeContent function to free the memory pointed to by this parameter.

    itemRef

    On return, a pointer to the item object of the Internet password. You are responsible for releasing your reference to this object. Pass NULL if you don’t want to obtain this object.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function finds the first Internet password item that matches the attributes you provide. This function optionally returns a reference to the found item.

    This function decrypts the password before returning it to you. If the calling application is not in the list of trusted applications, the user is prompted before access is allowed. If the access controls for this item do not allow decryption, the function returns the errSecAuthFailed result code.

    This function automatically calls the function SecKeychainUnlock to display the Unlock Keychain dialog box if the keychain is currently locked.

    Availability

    Available in OS X v10.2 and later.

  • Adds a new generic password to a keychain.

    Declaration

    Swift

    func SecKeychainAddGenericPassword(_ keychain: SecKeychain?, _ serviceNameLength: UInt32, _ serviceName: UnsafePointer<Int8>, _ accountNameLength: UInt32, _ accountName: UnsafePointer<Int8>, _ passwordLength: UInt32, _ passwordData: UnsafePointer<Void>, _ itemRef: UnsafeMutablePointer<SecKeychainItem?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainAddGenericPassword ( SecKeychainRef keychain, UInt32 serviceNameLength, const char *serviceName, UInt32 accountNameLength, const char *accountName, UInt32 passwordLength, const void *passwordData, SecKeychainItemRef _Nullable *itemRef );

    Parameters

    keychain

    A reference to the keychain in which to store a generic password. Pass NULL to specify the default keychain.

    serviceNameLength

    The length of the serviceName character string.

    serviceName

    A UTF-8 encoded character string representing the service name.

    accountNameLength

    The length of the accountName character string.

    accountName

    A UTF-8 encoded character string representing the account name.

    passwordLength

    The length of the passwordData buffer.

    passwordData

    A pointer to a buffer containing the password data to be stored in the keychain. Before calling this function, allocate enough memory for the buffer to hold the data you want to store.

    itemRef

    On return, a pointer to a reference to the new keychain item. Pass NULL if you don’t want to obtain this object. You must allocate the memory for this pointer. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. The result code errSecNoDefaultKeychain indicates that no default keychain could be found. The result code errSecDuplicateItem indicates that you tried to add a password that already exists in the keychain. The result code errSecDataTooLarge indicates that you tried to add more data than is allowed for a structure of this type. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function adds a new generic password to the specified keychain. Required parameters to identify the password are serviceName and accountName, which are application-defined strings. This function optionally returns a reference to the newly added item.

    You can use this function to add passwords for accounts other than the Internet. For example, you might add AppleShare passwords, or passwords for your database or scheduling programs.

    This function sets the initial access rights for the new keychain item so that the application creating the item is given trusted access.

    This function automatically calls the function SecKeychainUnlock to display the Unlock Keychain dialog box if the keychain is currently locked.

    Availability

    Available in OS X v10.2 and later.

  • Finds the first generic password based on the attributes passed.

    Declaration

    Swift

    func SecKeychainFindGenericPassword(_ keychainOrArray: AnyObject?, _ serviceNameLength: UInt32, _ serviceName: UnsafePointer<Int8>, _ accountNameLength: UInt32, _ accountName: UnsafePointer<Int8>, _ passwordLength: UnsafeMutablePointer<UInt32>, _ passwordData: UnsafeMutablePointer<UnsafeMutablePointer<Void>>, _ itemRef: UnsafeMutablePointer<SecKeychainItem?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainFindGenericPassword ( CFTypeRef keychainOrArray, UInt32 serviceNameLength, const char *serviceName, UInt32 accountNameLength, const char *accountName, UInt32 *passwordLength, void * _Nullable *passwordData, SecKeychainItemRef _Nullable *itemRef );

    Parameters

    keychainOrArray

    A reference to an array of keychains to search, a single keychain, or NULL to search the user’s default keychain search list.

    serviceNameLength

    The length of the serviceName character string.

    serviceName

    A UTF-8 encoded character string representing the service name.

    accountNameLength

    The length of the accountName character string.

    accountName

    A UTF-8 encoded character string representing the account name.

    passwordLength

    On return, the length of the buffer pointed to by passwordData.

    passwordData

    On return, a pointer to a buffer that holds the password data. Pass NULL if you want to obtain the item object but not the password data. In this case, you must also pass NULL in the passwordLength parameter. You should use the SecKeychainItemFreeContent function to free the memory pointed to by this parameter.

    itemRef

    On return, a pointer to the item object of the generic password. You are responsible for releasing your reference to this object. Pass NULL if you don’t want to obtain this object.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function finds the first generic password item that matches the attributes you provide. Most attributes are optional; you should pass only as many as you need to narrow the search sufficiently for your application’s intended use. This function optionally returns a reference to the found item.

    This function decrypts the password before returning it to you. If the calling application is not in the list of trusted applications, the user is prompted before access is allowed. If the access controls for this item do not allow decryption, the function returns the errSecAuthFailed result code.

    This function automatically calls the function SecKeychainUnlock to display the Unlock Keychain dialog box if the keychain is currently locked.

    Availability

    Available in OS X v10.2 and later.

  • Specifies the list of keychains to use in the default keychain search list.

    Declaration

    Swift

    func SecKeychainSetSearchList(_ searchList: CFArray) -> OSStatus

    Objective-C

    OSStatus SecKeychainSetSearchList ( CFArrayRef searchList );

    Parameters

    searchList

    An array of keychain references (of type SecKeychainRef) specifying the list of keychains to use in the default keychain search list. Passing an empty array clears the search list.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    The default keychain search list is used by several functions; see for example SecKeychainSearchCreateFromAttributes, SecKeychainFindInternetPassword, or SecKeychainFindGenericPassword. To obtain the current default keychain search list, use the SecKeychainCopySearchList function.

    The default keychain search list is displayed as the keychain list in the Keychain Access utility. If you use SecKeychainSetSearchList to change the keychain search list, the list displayed in Keychain Access changes accordingly.

    Availability

    Available in OS X v10.2 and later.

  • Retrieves a keychain search list.

    Declaration

    Swift

    func SecKeychainCopySearchList(_ searchList: UnsafeMutablePointer<CFArray?>) -> OSStatus

    Objective-C

    OSStatus SecKeychainCopySearchList ( CFArrayRef _Nullable *searchList );

    Parameters

    searchList

    On return, the returned keychain search list. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.2 and later.

  • Creates a search object matching a list of zero or more attributes.

    Declaration

    Objective-C

    OSStatus SecKeychainSearchCreateFromAttributes ( CFTypeRef keychainOrArray, SecItemClass itemClass, const SecKeychainAttributeList *attrList, SecKeychainSearchRef _Nullable *searchRef );

    Parameters

    keychainOrArray

    A reference to an array of keychains to search, a single keychain, or NULL to search the user’s current keychain search list. Use the function SecKeychainCopySearchList to retrieve the user’s default search list.

    itemClass

    The keychain item class. See Keychain Item Class Constants for valid constants.

    attrList

    A pointer to a list of zero or more keychain attribute records to match. Pass NULL to match any keychain attribute.

    searchRef

    On return, a pointer to the current search object. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Each item stored in the keychain contains data (such as a certificate), which is indexed by the item’s attributes. You look up an item in a keychain by its attributes. If you find a match, you can then retrieve the item’s data. Use the search object created by this function as input to the SecKeychainSearchCopyNext function to find a a keychain item and the SecKeychainItemCopyAttributesAndData function to retrieve the item’s data.

    To find and obtain data from a password keychain item, use the SecKeychainFindInternetPassword or SecKeychainFindGenericPassword function.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Finds the next keychain item matching the given search criteria.

    Declaration

    Objective-C

    OSStatus SecKeychainSearchCopyNext ( SecKeychainSearchRef searchRef, SecKeychainItemRef _Nullable *itemRef );

    Parameters

    searchRef

    A reference to the current search criteria. The search object is created in the SecKeychainSearchCreateFromAttributes function and must be released by calling the CFRelease function when you are done with it.

    itemRef

    On return, a pointer to a keychain item object of the next matching keychain item, if any. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. When there are no more items that match, errSecItemNotFound is returned. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Each item stored in the keychain contains data (such as a certificate), which is indexed by the item’s attributes. Use the SecKeychainSearchCreateFromAttributes function to specify attributes to search for. If the SecKeychainSearchCopyNext function finds a match, you can use the SecKeychainItemCopyAttributesAndData function to retrieve the item’s data.

    A SecKeychainItemRef object for a certificate that is stored in a keychain can be safely cast to a SecCertificateRef for use with the Certificate, Key, and Trust API.

    To find and obtain data from a password keychain item, use the SecKeychainFindInternetPassword or SecKeychainFindGenericPassword function.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Exports one or more certificates, keys, or identities.

    Declaration

    Swift

    func SecItemExport(_ secItemOrArray: AnyObject, _ outputFormat: SecExternalFormat, _ flags: SecItemImportExportFlags, _ keyParams: UnsafePointer<SecItemImportExportKeyParameters>, _ exportedData: UnsafeMutablePointer<CFData?>) -> OSStatus

    Objective-C

    OSStatus SecItemExport ( CFTypeRef secItemOrArray, SecExternalFormat outputFormat, SecItemImportExportFlags flags, const SecItemImportExportKeyParameters *keyParams, CFDataRef _Nullable *exportedData );

    Parameters

    secItemOrArray

    The keychain item or items to export. You can export only the following types of keychain items: SecCertificateRef, SecKeyRef, and SecIdentityRef. If you are exporting exactly one item, you can specify a SecKeychainItemRef object. Otherwise this parameter is a CFArrayRef object containing a number of items of type SecKeychainItemRef.

    outputFormat

    The format of the desired external representation for the item. Set this parameter to kSecFormatUnknown to use the default for that item type. Possible values for this parameter and default values are enumerated in Keychain Item Import/Export Formats.

    flags

    A flag field indicating whether the exported item should have PEM armor. PEM armor refers to a way of expressing binary data as an ASCII string so that it can be transferred over text-only channels such as email. Set this flag to kSecItemPemArmour if you want PEM armoring.

    keyParams

    A pointer to a structure containing a set of input parameters for the function. If no key items are being exported, these parameters are optional and you can set the keyParams parameter to NULL. For more information, see SecItemImportExportKeyParameters.

    exportedData

    On return, the variable referenced by this argument is overwritten with a CFDataRef object containing the external representation of the keychain item or items. You are responsible for releasing this object by calling CFRelease.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function works only with keys, certificates, and identities. An identity is the combination of a certificate and its associated private key. Although public keys are commonly stored in certificates, they can be stored separately in the keychain as well; for example, when you call the SecKeyCreatePair function to create a key pair, both the public and private keys are stored in the keychain. Use the SecKeychainSearchCopyNext function to find a key or certificate. Use the SecIdentitySearchCopyNext function in the Certificate, Key, and Trust API to find an identity.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Exports one or more certificates, keys, or identities.

    Declaration

    Objective-C

    OSStatus SecKeychainItemExport ( CFTypeRef keychainItemOrArray, SecExternalFormat outputFormat, SecItemImportExportFlags flags, const SecKeyImportExportParameters *keyParams, CFDataRef _Nullable *exportedData );

    Parameters

    keychainItemOrArray

    The keychain item or items to export. You can export only the following types of keychain items: SecCertificateRef, SecKeyRef, and SecIdentityRef. If you are exporting exactly one item, you can specify a SecKeychainItemRef object. Otherwise this parameter is a CFArrayRef object containing a number of items of type SecKeychainItemRef.

    outputFormat

    The format of the desired external representation for the item. Set this parameter to kSecFormatUnknown to use the default for that item type. Possible values for this parameter and default values are enumerated in Keychain Item Import/Export Formats.

    flags

    A flag indicating whether the exported item should have PEM armor. PEM armor refers to a way of expressing binary data as an ASCII string so that it can be transferred over text-only channels such as email. Set this flag to kSecItemPemArmour if you want PEM armoring.

    keyParams

    A pointer to a structure containing a set of input parameters for the function. If no key items are being exported, these parameters are optional and you can set the keyParams parameter to NULL.

    exportedData

    On return, points to the external representation of the keychain item or items.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function works only with keys, certificates, and identities. An identity is the combination of a certificate and its associated private key. Although public keys are commonly stored in certificates, they can be stored separately in the keychain as well; for example, when you call the SecKeyCreatePair function to create a key pair, both the public and private keys are stored in the keychain. Use the SecKeychainSearchCopyNext function to find a key or certificate. Use the SecIdentitySearchCopyNext function in the Certificate, Key, and Trust API to find an identity.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecItemExport instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Converts an external representation of a keychain item or items into SecKeychainItem objects and optionally imports them into a specified keychain.

    Declaration

    Swift

    func SecItemImport(_ importedData: CFData, _ fileNameOrExtension: CFString?, _ inputFormat: UnsafeMutablePointer<SecExternalFormat>, _ itemType: UnsafeMutablePointer<SecExternalItemType>, _ flags: SecItemImportExportFlags, _ keyParams: UnsafePointer<SecItemImportExportKeyParameters>, _ importKeychain: SecKeychain?, _ outItems: UnsafeMutablePointer<CFArray?>) -> OSStatus

    Objective-C

    OSStatus SecItemImport ( CFDataRef importedData, CFStringRef fileNameOrExtension, SecExternalFormat *inputFormat, SecExternalItemType *itemType, SecItemImportExportFlags flags, const SecItemImportExportKeyParameters *keyParams, SecKeychainRef importKeychain, CFArrayRef _Nullable *outItems );

    Parameters

    importedData

    A CFDataRef object containing the data to import.

    fileNameOrExtension

    Optional. The name of the file from which the external representation was previously read, or if that is unknown, then the file extension (.p7r, for example). This serves as a hint for the key format and key type detection code.

    inputFormat

    Optional. The address of a SecExternalFormat variable.

    If you know what format the external representation is in, you should set the initial value of this variable to an appropriate format constant (Keychain Item Import/Export Formats) to eliminate the need to detect the format. If not, set it to kSecFormatUnknown.

    On return, the variable referenced by this argument is set to the format that the function actually detected.

    Pass NULL if you neither know nor care what format the external representation is in.

    itemType

    Optional. The address of a SecExternalItemType variable.

    Before calling this function, if you know what type of key the external representation contains, you should set the variable to an appropriate type constant (Keychain Item Type When Importing) to eliminate the need to detect the key type. If not, set it to kSecItemTypeUnknown.

    On return, the variable referenced by this argument is set to the type of key that the function actually detected.

    Pass NULL if you neither know nor care what key type the external representation contains.

    flags

    A set of import flags (Keychain Item Import/Export Flags).

    Note that PEM formatting is determined internally via inspection of the incoming data, so the kSecItemPemArmour flag is ignored.

    keyParams

    A pointer to a structure containing a set of input parameters for the function. For more information, see SecItemImportExportKeyParameters.

    importKeychain

    Optional. The keychain into which the item should be imported. Pass NULL if you do not want to import the item into a keychain.

    outItems

    Optional. The address of a CFArrayRef variable that, upon return, will contain a list of keychain items. Pass NULL if you do not want a copy of these items.

    Upon return, the referenced variable is overwritten by a new CFArrayRef array that contains SecKeychainItem objects, each of which may be a SecCertificateRef, SecKeyRef, or SecIdentityRef object. The caller is responsible for releasing this CFArrayRef object.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    The SecItemImport function uses the fileNameOrExtension, inputFormat, and itemType parameters to help it interpret the incoming data. In most cases, SecItemImport can correctly interpret an external item if none of these are specified, but it is unwise for an application to count on that ability.

    When the output item type is kSecItemTypeAggregate, you can use the CFGetTypeID function to determine the Core Foundation type of each item and the functions in Getting Information About Keychain Services and Types to determine the keychain item type of each item. For example, the following code determines whether the item is a certificate:

    1. CFTypeID theID = CFGetTypeID(theItem);
    2. if (SecCertificateGetTypeID() == theID)

    You can pass in NULL for both outItems and importKeychain to determine what is inside a given external data representation. When you do, the function returns the input format and the item type without modifying the data in any way.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Imports one or more certificates, keys, or identities and adds them to a keychain.

    Declaration

    Objective-C

    OSStatus SecKeychainItemImport ( CFDataRef importedData, CFStringRef fileNameOrExtension, SecExternalFormat *inputFormat, SecExternalItemType *itemType, SecItemImportExportFlags flags, const SecKeyImportExportParameters *keyParams, SecKeychainRef importKeychain, CFArrayRef _Nullable *outItems );

    Parameters

    importedData

    The external representation of the items to import.

    fileNameOrExtension

    The name or extension of the file from which the external representation was obtained. Pass NULL if you don’t know the name or extension.

    inputFormat

    On entry, points to the format of the external representation. Pass kSecFormatUnknown if you do not know the exact format. On return, points to the format that the function has determined the external representation to be in. Pass NULL if you don’t know the format and don’t want the format returned to you. For a list of formats, see Keychain Item Import/Export Formats.

    itemType

    On entry, points to the item type of the item or items contained in the external representation. Pass kSecItemTypeUnknown if you do not know the item type. On return, points to the item type that the function has determined the external representation to contain. Pass NULL if you don’t know the item type and don’t want the type returned to you.

    flags

    Unused; pass in 0.

    keyParams

    A pointer to a structure containing a set of input parameters for the function. If no key items are being imported, these parameters are optional and you can set the keyParams parameter to NULL. If you pass NULL for the importKeychain parameter, the kSecKeyImportOnlyOne bit in the flags field of the SecKeyImportExportParameters structure is ignored. Otherwise, if the kSecKeyImportOnlyOne bit is set and there is more than one private key in the incoming external representation, no items are imported to the specified keychain and the error errSecMultiplePrivKeys is returned. The possible values for the flags field are described in Keychain Item Import/Export Parameter Flags.

    importKeychain

    A keychain object indicating the keychain to which the key or certificate should be imported. If you pass NULL, the item is not imported. Use the SecKeychainCopyDefault function to get a reference to the default keychain.

    outItems

    On return, points to an array of SecKeychainItemRef objects for the imported items. You must provide a valid pointer to a CFArrayRef object to receive this information. If you pass NULL for this parameter, the function does not return the imported items. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    When you pass this function a CFDataRef object containing the external representation of one or more keys, certificates, or identities, SecKeychainItemImport attempts to determine the format and contents of the data. To ensure that this process is successful, you should specify values for one or more of the parameters fileNameOrExtension, inputFormat, and itemType. To have the function add the imported items to a keychain, specify a non-NULL value for the importKeychain parameter. To have the function return SecKeychainItemRef objects for the imported items, specify a non-NULL value for the outItems parameter.

    Because the SecKeychainItemImport function determines whether the item is PEM armored by inspecting the data, the flags parameter is not used in calling this function.

    After the function returns, you can determine the nature of the keychain items from the values returned in the inputFormat and itemType parameters. Depending on the nature of each item, once it is imported to a keychain you can safely cast the SecKeychainItemRef object to a SecKeyRef, SecCertificateRef, or SecIdentityRef object.

    Note that when you import data in PKCS12 format, typically one SecIdentityRef object is returned in the outItems parameter. The data might also include one or more SecCertificateRef objects. The output data will not include any SecKeyRef objects unless the incoming data includes a key with no matching certificate.

    When the output item type is kSecItemTypeAggregate, you can use the CFGetTypeID function to determine the Core Foundation type of each item and the functions in Getting Information About Keychain Services and Types to determine the keychain item type of each item. For example, the following code determines whether the item is a certificate:

    1. CFTypeID theID = CFGetTypeID(theItem);
    2. if (SecCertificateGetTypeID() == theID)

    You can pass in NULL for both outItems and importKeychain to determine what is inside a given external data representation. When you do, the function returns the input format and the item type without modifying the data in any way.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecItemImport instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Creates a new access object.

    Declaration

    Swift

    func SecAccessCreate(_ descriptor: CFString, _ trustedlist: CFArray?, _ accessRef: UnsafeMutablePointer<SecAccess?>) -> OSStatus

    Objective-C

    OSStatus SecAccessCreate ( CFStringRef descriptor, CFArrayRef trustedlist, SecAccessRef _Nullable *accessRef );

    Parameters

    descriptor

    A CFString object representing the name of the keychain item as it should appear in security dialogs. Note that this is not necessarily the same name as appears for that item in the Keychain Access application.

    trustedlist

    A reference to an array of trusted application objects (values of type SecTrustedApplicationRef) specifying which applications should be allowed to access the item without triggering confirmation dialogs. Use the SecTrustedApplicationCreateFromPath function to create trusted application objects. If you pass NULL for this parameter, the access control list is automatically set to the application creating the item. To set no applications, pass a CFArrayRef with no elements.

    accessRef

    On return, points to the new access object. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Each protected keychain item (such as a password or private key) has an associated access object. The access object contains access control list (ACL) entries, which specify trusted applications and the operations for which those operations are trusted. When an application attempts to access a keychain item for a particular purpose (such as to sign a document), the system determines whether that application is trusted to access the item for that purpose. If it is trusted, then the application is given access and no user confirmation is required. If the application is not trusted, but there is an ACL entry for that operation, then the user is asked to confirm whether the application should be given access. If there is no ACL entry for that operation, then access is denied and it is up to the calling application to try something else or to notify the user.

    This function creates an access object with three ACL entries: The first, referred to as owner access, determines who can modify the access object itself. By default, there are no trusted applications for owner access; the user is always prompted for permission if someone tries to change access controls. The second is for operations considered safe, such as encrypting data. This ACL entry applies to all applications. The third ACL entry is for operations that should be restricted, such as decrypting, signing, deriving keys, and exporting keys. This ACL entry applies to the trusted applications listed in the trustedlist parameter.

    To retrieve all the ACL entries of an access object, use the SecAccessCopyACLList function. To retrieve specific ACL entries, use the SecAccessCopySelectedACLList function. To create a new ACL entry and add it to an access object, use SecACLCreateFromSimpleContents. To modify an existing ACL entry, use SecACLSetSimpleContents. To modify the operations for which an ACL entry is used, call the SecACLSetAuthorizations function.

    Because an ACL object is always associated with an access object, when you modify an ACL entry, you are modifying the access object as well. Therefore, there is no need for a separate function to write a modified ACL object back into the access object.

    Availability

    Available in OS X v10.2 and later.

  • Creates a new access object using the owner and access control list you provide.

    Declaration

    Swift

    func SecAccessCreateWithOwnerAndACL(_ userId: uid_t, _ groupId: gid_t, _ ownerType: SecAccessOwnerType, _ acls: CFArray?, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>) -> SecAccess?

    Objective-C

    SecAccessRef SecAccessCreateWithOwnerAndACL ( uid_t userId, gid_t groupId, SecAccessOwnerType ownerType, CFArrayRef acls, CFErrorRef _Nullable *error );

    Parameters

    userId

    The user ID that owns this access control list.

    groupId

    The group ID that owns this access control list.

    ownerType

    Flags that control whether the specified user ID or group ID owns the resulting access control list. See SecAccessOwnerType for details.

    acls

    An array of access control list entries to associate with the access object.

    error

    The address of a CFErrorRef variable. On error, the return value is NULL, and the variable referenced by this parameter is overwritten with a CFError object that provides more information.

    Return Value

    Returns the new access object. You must call the CFRelease function to release this object when you are finished using it.

    Discussion

    You can use this function to create an access object for use with other Certificate, Key, and Trust API functions if you want to create the access control list yourself. This allows more complex access controls than you can construct with the Certificate, Key, and Trust API.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Creates a new access object using the owner and access control list you provide.

    Declaration

    Objective-C

    OSStatus SecAccessCreateFromOwnerAndACL ( const CSSM_ACL_OWNER_PROTOTYPE *owner, uint32 aclCount, const CSSM_ACL_ENTRY_INFO *acls, SecAccessRef _Nullable *accessRef );

    Parameters

    owner

    A pointer to a CSSM access control list owner.

    aclCount

    An unsigned 32-bit integer representing the number of items in the access control list.

    acls

    A pointer to the CSSM access control list.

    accessRef

    On return, points to the new access object. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function creates an access object from CSSM structures. You can use this function to create an access object for use with other Certificate, Key, and Trust API functions if you want to use CSSM to create the access control list. CSSM allows more complex access controls than you can construct with the Certificate, Key, and Trust API. For more information about the CSSM API, see Common Security: CDSA and CSSM, version 2 (with corrigenda) from The Open Group (http://www.opengroup.org/security/cdsa.htm).

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecAccessCreateWithOwnerAndACL instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Retrieves all the access control list entries of a given access object.

    Declaration

    Swift

    func SecAccessCopyACLList(_ accessRef: SecAccess, _ aclList: UnsafeMutablePointer<CFArray?>) -> OSStatus

    Objective-C

    OSStatus SecAccessCopyACLList ( SecAccessRef accessRef, CFArrayRef _Nullable *aclList );

    Parameters

    accessRef

    The access object from which to retrieve the information.

    aclList

    On return, a pointer to a reference of a newly created CFArray of SecACLRef instances. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    An access object can have any number of access control list (ACL) entries for specific operations or sets of operations. To retrieve ACL entries for specific operations, use the SecAccessCopySelectedACLList function.

    Availability

    Available in OS X v10.2 and later.

  • Retrieves selected access control lists from a given access object.

    Declaration

    Swift

    func SecAccessCopyMatchingACLList(_ accessRef: SecAccess, _ authorizationTag: AnyObject) -> CFArray?

    Objective-C

    CFArrayRef SecAccessCopyMatchingACLList ( SecAccessRef accessRef, CFTypeRef authorizationTag );

    Parameters

    accessRef

    The access object from which to retrieve the information.

    authorizationTag

    An access control list authorization tag; the function returns only those access control list entries that apply to the operation indicated by this tag. See CSSM Authorization Tag Type Constants for details.

    Return Value

    Returns an array containing the selected access control lists. You must call the CFRelease function to release this object when you are finished using it.

    Discussion

    An access object can have any number of access control list (ACL) entries for specific operations or sets of operations. To retrieve all the ACL entries for an access object, use the SecAccessCopyACLList function.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Retrieves selected access control lists from a given access object.

    Declaration

    Objective-C

    OSStatus SecAccessCopySelectedACLList ( SecAccessRef accessRef, CSSM_ACL_AUTHORIZATION_TAG action, CFArrayRef _Nullable *aclList );

    Parameters

    accessRef

    The access object from which to retrieve the information.

    action

    An access control list authorization tag; the function returns only those access control list entries that apply to the operation indicated by this tag.

    aclList

    On return, a pointer to the selected access control lists. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    An access object can have any number of access control list (ACL) entries for specific operations or sets of operations. To retrieve all the ACL entries for an access object, use the SecAccessCopyACLList function.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecAccessCopyMatchingACLList instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Retrieves the owner and the access control list of a given access object.

    Declaration

    Swift

    func SecAccessCopyOwnerAndACL(_ accessRef: SecAccess, _ userId: UnsafeMutablePointer<uid_t>, _ groupId: UnsafeMutablePointer<gid_t>, _ ownerType: UnsafeMutablePointer<SecAccessOwnerType>, _ aclList: UnsafeMutablePointer<CFArray?>) -> OSStatus

    Objective-C

    OSStatus SecAccessCopyOwnerAndACL ( SecAccessRef accessRef, uid_t *userId, gid_t *groupId, SecAccessOwnerType *ownerType, CFArrayRef _Nullable *aclList );

    Parameters

    accessRef

    An access object from which to retrieve the owner and access control list.

    userId

    On return, the user ID that owns the access object.

    groupId

    On return, the user ID that owns the access object.

    ownerType

    On return, flags that indicate whether the specified user ID or group ID owns the resulting access control list. See SecAccessOwnerType for details.

    aclList

    On return, an array of access control list entries associated with the access object.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Retrieves the owner and the access control list of a given access object.

    Declaration

    Objective-C

    OSStatus SecAccessGetOwnerAndACL ( SecAccessRef accessRef, CSSM_ACL_OWNER_PROTOTYPE_PTR _Nullable *owner, uint32 *aclCount, CSSM_ACL_ENTRY_INFO_PTR _Nullable *acls );

    Parameters

    accessRef

    An access object from which to retrieve the owner and access control list.

    owner

    On return, a pointer to a CSSM access control list owner.

    aclCount

    On return, a pointer to an unsigned 32-bit integer representing the number of items in the access control list.

    acls

    On return, a pointer to the CSSM access control list.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function returns CSSM structures for use with CSSM API functions.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecAccessCreateWithOwnerAndACL instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Creates a new access control object with the specified on protection type and flags.

    Declaration

    Swift

    func SecAccessControlCreateWithFlags(_ allocator: CFAllocator?, _ protection: AnyObject, _ flags: SecAccessControlCreateFlags, _ error: UnsafeMutablePointer<Unmanaged<CFError>?>) -> SecAccessControl?

    Objective-C

    SecAccessControlRef SecAccessControlCreateWithFlags ( CFAllocatorRef allocator, CFTypeRef protection, SecAccessControlCreateFlags flags, CFErrorRef _Nullable *error );

    Parameters

    allocator

    The allocator to use to allocate memory for the new SecAccessControlRef object. Pass NULL or kCFAllocatorDefault to allocate memory for the new allocator using the default allocator.

    protection

    Protection class to be used for the item. Use one of the kSecAttrAccessible constants.

    flags

    Flags specifying the allowed operations for the item. See SecAccessControlCreateWithFlags.

    error

    On return, the variable referenced by this parameter will contain an error object, if any error occurred.

    Discussion

    You use the result of this function as a value for the kSecAttrAccessControl attribute in the SecItemAdd, SecItemUpdate, or SecKeyGeneratePair functions.

    Accessing keychain items or performing operations on keys that are protected by access control objects may block execution on the main thread. You should only perform these actions in the background, or use them in combination with the kSecUseAuthenticationContext and kSecUseAuthenticationUI attributes to manage user interactions.

    Availability

    Available in OS X v10.10 and later.

  • Creates a new access control list entry from the application list, description, and prompt selector provided and adds it to an item’s access object.

    Declaration

    Swift

    func SecACLCreateWithSimpleContents(_ access: SecAccess, _ applicationList: CFArray?, _ description: CFString, _ promptSelector: SecKeychainPromptSelector, _ newAcl: UnsafeMutablePointer<SecACL?>) -> OSStatus

    Objective-C

    OSStatus SecACLCreateWithSimpleContents ( SecAccessRef access, CFArrayRef applicationList, CFStringRef description, SecKeychainPromptSelector promptSelector, SecACLRef _Nullable *newAcl );

    Parameters

    access

    The access object to which to add the information.

    applicationList

    An array of trusted application objects (that is, SecTrustedApplication instances) identifying applications that are allowed access to the keychain item without user confirmation. Use the SecTrustedApplicationCreateFromPath function to create trusted application objects. If you set this parameter to NULL, then any application can use this item. If you pass an empty array, then there are no trusted applications. You must call the CFRelease function to release this object when you are finished using it.

    description

    The human readable name to be used to refer to this item when the user is prompted.

    promptSelector

    A set of prompt selector flags. See SecKeychainPromptSelector for possible values.

    newAcl

    On return, the variable referenced by this parameter will contain an object representing the new access control list entry.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    The ACL object returned by this function is a reference to an access control list (ACL) entry. The ACL entry includes a list of trusted applications (see SecTrustedApplicationCreateFromPath), the name of the keychain item as it appears in user prompts, the prompt selector flag, and a list of one or more operations to which this ACL entry applies. By default, a new ACL entry applies to all operations (the CSSM authorization tag is set to CSSM_ACL_AUTHORIZATION_ANY). Use the SecACLUpdateAuthorizations function to set the list of operations for an ACL object.

    The system allows exactly one owner ACL entry in each access object. The SecACLCreateWithSimpleContents function fails if you attempt to add a second owner ACL. To change owner access controls, use the SecAccessCopyMatchingACLList function to find the owner ACL (that is, the only ACL with a CSSM authorization tag of CSSM_ACL_AUTHORIZATION_CHANGE_ACL) and the SecACLSetContents function to change it as needed.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Creates a new access control list entry from the application list, description, and prompt selector provided and adds it to an item’s access object.

    Declaration

    Objective-C

    OSStatus SecACLCreateFromSimpleContents ( SecAccessRef access, CFArrayRef applicationList, CFStringRef description, const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector, SecACLRef _Nullable *newAcl );

    Parameters

    access

    The access object to which to add the information.

    applicationList

    An array of trusted application objects (that is, SecTrustedApplication instances) identifying applications that are allowed access to the keychain item without user confirmation. Use the SecTrustedApplicationCreateFromPath function to create trusted application objects. If you set this parameter to NULL, then any application can use this item. If you pass an empty array, then there are no trusted applications. You must call the CFRelease function to release this object when you are finished using it.

    description

    The human readable name to be used to refer to this item when the user is prompted.

    promptSelector

    A pointer to a prompt selector. If you set the CSSM_ACL_KEYCHAIN_PROMPT_REQUIRE_PASSPHRASE bit, the user is prompted for the keychain password each time a non-trusted application attempts to access this item, even if the keychain is already unlocked.

    newAcl

    On return, points to an access control list object, which is a reference to the new access control list entry.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    The ACL object returned by this function is a reference to an access control list (ACL) entry. The ACL entry includes a list of trusted applications (see SecTrustedApplicationCreateFromPath), the name of the keychain item as it appears in user prompts, the prompt selector flag, and a list of one or more operations to which this ACL entry applies. By default, a new ACL entry applies to all operations (the CSSM authorization tag is set to CSSM_ACL_AUTHORIZATION_ANY). Use the SecACLSetAuthorizations function to set the list of operations for an ACL object.

    The system allows exactly one owner ACL entry in each access object. The SecACLCreateFromSimpleContents function fails if you attempt to add a second owner ACL. To change owner access controls, use the SecAccessCopySelectedACLList function to find the owner ACL (that is, the only ACL with a CSSM authorization tag of CSSM_ACL_AUTHORIZATION_CHANGE_ACL) and the SecACLSetSimpleContents function to change it as needed.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecACLCreateWithSimpleContents instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Removes the specified access control list entry.

    Declaration

    Swift

    func SecACLRemove(_ aclRef: SecACL) -> OSStatus

    Objective-C

    OSStatus SecACLRemove ( SecACLRef aclRef );

    Parameters

    aclRef

    An ACL object that identifies the access control list entry to remove.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    The system allows exactly one owner ACL entry in each access object. The SecACLRemove function fails if you attempt to remove the owner ACL entry. To change owner access controls, use the SecAccessCopySelectedACLList function to find the owner ACL (that is, the only ACL with a CSSM authorization tag of CSSM_ACL_AUTHORIZATION_CHANGE_ACL) and the SecACLSetSimpleContents function to change it as needed.

    Availability

    Available in OS X v10.3 and later.

  • Returns the application list, description, and prompt selector for a given access control list entry.

    Declaration

    Swift

    func SecACLCopyContents(_ acl: SecACL, _ applicationList: UnsafeMutablePointer<CFArray?>, _ description: UnsafeMutablePointer<CFString?>, _ promptSelector: UnsafeMutablePointer<SecKeychainPromptSelector>) -> OSStatus

    Objective-C

    OSStatus SecACLCopyContents ( SecACLRef acl, CFArrayRef _Nullable *applicationList, CFStringRef _Nullable *description, SecKeychainPromptSelector *promptSelector );

    Parameters

    acl

    An ACL object that identifies the access control list entry from which you want information.

    applicationList

    The address of a CFArrayRef variable into which a copy of the application list should be stored on return. This array will contain SecTrustedApplication instances identifying applications that are allowed access to the keychain item without user confirmation.

    If the resulting CFArrayRef value is NULL, then any application can use this item. If the resulting array reference is a valid pointer to an empty array, then there are no trusted applications.

    You must call the CFRelease function to release this object when you are finished using it.

    description

    The address of a CFStringRef variable into which a copy of the description should be stored on return. This description is the name of the keychain item that appears in the dialog box when the user is prompted for permission to use the item.

    Note that this name is not necessarily the same as the name displayed for the item by the Keychain Access application.

    You must call the CFRelease function to release this object when you are finished using it.

    promptSelector

    The address of a SecKeychainPromptSelector variable into which a copy of the prompt selector should be stored on return.

    On return, points to the prompt selector flag for the given access control list entry. If the kSecKeychainPromptRequirePassphase bit is set, the user is prompted for the keychain password each time a non-trusted application attempts to access this item, even if the keychain is already unlocked.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    An access control list entry applies to a specific use or set of uses for a specific keychain item. The ACL object includes a list of trusted applications (see SecTrustedApplicationCreateFromPath), the name of the keychain item as it appears in user prompts, the prompt selector flag, and a list of one or more operations to which this ACL object applies. Use the SecACLCopyAuthorizations function to get the list of operations for an ACL object.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Returns the application list, description, and CSSM prompt selector for a given access control list entry.

    Declaration

    Objective-C

    OSStatus SecACLCopySimpleContents ( SecACLRef acl, CFArrayRef _Nullable *applicationList, CFStringRef _Nullable *description, CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector );

    Parameters

    acl

    An ACL object that identifies the access control list entry from which you want information.

    applicationList

    On return, points to an array of SecTrustedApplication instances identifying applications that are allowed access to the keychain item without user confirmation. If this parameter returns NULL, then any application can use this item. If this parameter returns a valid pointer but the array is empty, then there are no trusted applications. You must call the CFRelease function to release this object when you are finished using it.

    description

    On return, the name of the keychain item that appears in the dialog box when the user is prompted for permission to use the item. Note that this name is not necessarily the same as the one displayed for the item by the Keychain Access application. You must call the CFRelease function to release this object when you are finished using it.

    promptSelector

    On return, points to the prompt selector flag for the given access control list entry. If the CSSM_ACL_KEYCHAIN_PROMPT_REQUIRE_PASSPHRASE bit is set, the user is prompted for the keychain password each time a non-trusted application attempts to access this item, even if the keychain is already unlocked.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    An access control list entry applies to a specific use or set of uses for a specific keychain item. The ACL object includes a list of trusted applications (see SecTrustedApplicationCreateFromPath), the name of the keychain item as it appears in user prompts, the prompt selector flag, and a list of one or more operations to which this ACL object applies. Use the SecACLGetAuthorizations function to get the list of operations for an ACL object.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecACLCopyContents instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Sets the application list, description, and prompt selector for a given access control list entry.

    Declaration

    Swift

    func SecACLSetContents(_ acl: SecACL, _ applicationList: CFArray?, _ description: CFString, _ promptSelector: SecKeychainPromptSelector) -> OSStatus

    Objective-C

    OSStatus SecACLSetContents ( SecACLRef acl, CFArrayRef applicationList, CFStringRef description, SecKeychainPromptSelector promptSelector );

    Parameters

    acl

    An ACL object that identifies the access control list entry.

    applicationList

    An array of trusted application objects (that is, SecTrustedApplication instances) identifying applications that are allowed access to the keychain item without user confirmation. Use the SecTrustedApplicationCreateFromPath function to create trusted application objects. If you set this parameter to NULL, then any application can use this item. If you pass an empty array, then all applications are treated as untrusted.

    description

    The name of the keychain item that appears in the dialog box when the user is prompted for permission to use the item. Note that this name is not necessarily the same as the one displayed for the item by the Keychain Access application.

    promptSelector

    The prompt selector flags for the given access control list entry. See SecKeychainPromptSelector for details.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Because an ACL object is always associated with an access object, when you modify an ACL entry, you are modifying the access object as well. There is no need to call a separate function to write a modified ACL object back into the access object.

    Use the SecACLCopyAuthorizations function to get the list of operations for an ACL object.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Sets the application list, description, and prompt selector for a given access control list entry.

    Declaration

    Objective-C

    OSStatus SecACLSetSimpleContents ( SecACLRef acl, CFArrayRef applicationList, CFStringRef description, const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector );

    Parameters

    acl

    An ACL object that identifies the access control list entry.

    applicationList

    An array of trusted application objects (that is, SecTrustedApplication instances) identifying applications that are allowed access to the keychain item without user confirmation. Use the SecTrustedApplicationCreateFromPath function to create trusted application objects. If you set this parameter to NULL, then any application can use this item. If you pass an empty array, then all applications are treated as untrusted.

    description

    The name of the keychain item that appears in the dialog box when the user is prompted for permission to use the item. Note that this name is not necessarily the same as the one displayed for the item by the Keychain Access application.

    promptSelector

    The prompt selector flag for the given access control list entry. Set the CSSM_ACL_KEYCHAIN_PROMPT_REQUIRE_PASSPHRASE bit to have the user prompted for the keychain password each time a non-trusted application attempts to access this item, even if the keychain is already unlocked.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Because an ACL object is always associated with an access object, when you modify an ACL entry, you are modifying the access object as well. There is no need for a separate function to write a modified ACL object back into the access object.

    Use the SecACLGetAuthorizations function to get the list of operations for an ACL object.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecACLSetContents instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Retrieves the authorization tags of a given access control list entry.

    Declaration

    Swift

    func SecACLCopyAuthorizations(_ acl: SecACL) -> CFArray

    Objective-C

    CFArrayRef SecACLCopyAuthorizations ( SecACLRef acl );

    Parameters

    acl

    An ACL object that identifies the access control list entry from which you wish to retrieve the authorization tags.

    Return Value

    Returns a CFArrayRef object containing the authorizations for this ACL.

    Discussion

    An ACL object includes a list of trusted applications (see SecTrustedApplicationCreateFromPath), the name of the keychain item as it appears in user prompts, the prompt selector flag, and a list of one or more operations to which this ACL object applies. Use this function to retrieve the list of operations for an ACL object. Use the SecACLCopyContents function to retrieve the other information.

    The SecACLGetAuthorizations function returns an error if there are more tags to return than the number of elements you allocated in the tags array. A 20-element array should suffice for most purposes; however, you can test for the errSecBufferTooSmall error and increase the size of the array before calling the function again if necessary. Alternatively, you can call the function with a tag count of 0, read the value returned in the tagCount parameter, and then call the function again using that value.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Retrieves the CSSM authorization tags of a given access control list entry.

    Declaration

    Objective-C

    OSStatus SecACLGetAuthorizations ( SecACLRef acl, CSSM_ACL_AUTHORIZATION_TAG *tags, uint32 *tagCount );

    Parameters

    acl

    An ACL object that identifies the access control list entry from which you wish to retrieve the authorization tags.

    tags

    A pointer to an array of CSSM authorization tags. You must allocate this array before calling the function. On return, this array contains the authorization tags of the specified ACL entry.

    tagCount

    On entry, points to the number of elements in the array you passed in the tags parameter. On return, points to the number of tags actually returned or, in the case of an overflow, the number of tags required.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    An ACL object includes a list of trusted applications (see SecTrustedApplicationCreateFromPath), the name of the keychain item as it appears in user prompts, the prompt selector flag, and a list of one or more operations to which this ACL object applies. Use this function to retrieve the list of operations for an ACL object. Use the SecACLCopySimpleContents function to retrieve the other information.

    The SecACLGetAuthorizations function returns an error if there are more tags to return than the number of elements you allocated in the tags array. A 20-element array should suffice for most purposes; however, you can test for the errSecBufferTooSmall error and increase the size of the array before calling the function again if necessary. Alternatively, you can call the function with a tag count of 0, read the value returned in the tagCount parameter, and then call the function again using that value.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecACLCopyAuthorizations instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Sets the authorization tags for a given access control list entry.

    Declaration

    Swift

    func SecACLUpdateAuthorizations(_ acl: SecACL, _ authorizations: CFArray) -> OSStatus

    Objective-C

    OSStatus SecACLUpdateAuthorizations ( SecACLRef acl, CFArrayRef authorizations );

    Parameters

    acl

    An ACL object that identifies the access control list entry for which you wish to set authorization tags.

    authorizations

    An array of authorization tags. See CSSM Authorization Tag Type Constants for details.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    An ACL object includes a list of trusted applications (see SecTrustedApplicationCreateFromPath), the name of the keychain item as it appears in user prompts, the prompt selector flag, and a list of one or more operations to which this ACL object applies. Use this function to set a list of operations for an ACL object, or set the CSSM_ACL_AUTHORIZATION_ANY tag to allow all operations. Use the SecACLSetContents function to set the other information.

    Because an ACL object is always associated with an access object, when you modify an ACL entry, you are modifying the access object as well. There is no need to call a separate function to write a modified ACL object back into the access object.

    Availability

    Available in OS X v10.7 and later.

  • Deprecated. Sets the CSSM authorization tags for a given access control list entry.

    Declaration

    Objective-C

    OSStatus SecACLSetAuthorizations ( SecACLRef acl, CSSM_ACL_AUTHORIZATION_TAG *tags, uint32 tagCount );

    Parameters

    acl

    An ACL object that identifies the access control list entry for which you wish to set authorization tags.

    tags

    An array of CSSM authorization tags.

    tagCount

    The number of tags in the CSSM authorization tag array.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    An ACL object includes a list of trusted applications (see SecTrustedApplicationCreateFromPath), the name of the keychain item as it appears in user prompts, the prompt selector flag, and a list of one or more operations to which this ACL object applies. Use this function to set a list of operations for an ACL object, or set the CSSM_ACL_AUTHORIZATION_ANY tag to allow all operations. Use the SecACLSetSimpleContents function to set the other information.

    Because an ACL object is always associated with an access object, when you modify an ACL entry, you are modifying the access object as well. There is no need for a separate function to write a modified ACL object back into the access object.

    Special Considerations

    This function is deprecated in OS X v10.7 and later; use SecACLUpdateAuthorizations instead.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Retrieves the data of a trusted application object.

    Declaration

    Swift

    func SecTrustedApplicationCopyData(_ appRef: SecTrustedApplication, _ data: UnsafeMutablePointer<CFData?>) -> OSStatus

    Objective-C

    OSStatus SecTrustedApplicationCopyData ( SecTrustedApplicationRef appRef, CFDataRef _Nullable *data );

    Parameters

    appRef

    A trusted application object from which to retrieve data. Use the SecTrustedApplicationCreateFromPath function to create a trusted application object.

    data

    On return, points to a data object for the data of the trusted application object. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    The trusted application object created by the SecTrustedApplicationCreateFromPath function includes data that uniquely identifies the application, such as a cryptographic hash of the application. The operating system can use this data to verify that the application has not been altered since the trusted application object was created. When an application requests access to an item in the keychain for which it is designated as a trusted application, for example, the operating system checks this data before granting access. You can use the SecTrustedApplicationCopyData function to extract this data from the trusted application object for storage or for transmittal to another location (such as over a network). Use the SecTrustedApplicationSetData function to insert the data back into a trusted application object. Note that this data is in a private format; there is no supported way to read or interpret it.

    Availability

    Available in OS X v10.2 and later.

  • Creates a trusted application object based on the application specified by path.

    Declaration

    Swift

    func SecTrustedApplicationCreateFromPath(_ path: UnsafePointer<Int8>, _ app: UnsafeMutablePointer<SecTrustedApplication?>) -> OSStatus

    Objective-C

    OSStatus SecTrustedApplicationCreateFromPath ( const char *path, SecTrustedApplicationRef _Nullable *app );

    Parameters

    path

    The path to the application or tool to trust. For application bundles, use the path to the bundle directory. Pass NULL to refer to the application or tool making this call.

    app

    On return, points to the newly created trusted application object. You must call the CFRelease function to release this object when you are finished using it.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    This function creates a trusted application object, which both identifies an application and provides data that can be used to ensure that the application has not been altered since the object was created. The application object is used as input to the SecAccessCreate function, which creates an access object. The access object, in turn, is used as input to the SecKeychainItemSetAccess function to specify the set of applications that are trusted to access a specific keychain item.

    Availability

    Available in OS X v10.2 and later.

  • Sets the data of a given trusted application object.

    Declaration

    Swift

    func SecTrustedApplicationSetData(_ appRef: SecTrustedApplication, _ data: CFData) -> OSStatus

    Objective-C

    OSStatus SecTrustedApplicationSetData ( SecTrustedApplicationRef appRef, CFDataRef data );

    Parameters

    appRef

    A trusted application object.

    data

    A reference to the data to set in the trusted application.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    If you used the SecTrustedApplicationCopyData function to extract the data from a trusted application object for storage or to transmit it to a different location, you can use the SecTrustedApplicationSetData function to insert the data into a new trusted application object. Doing so would create an object that identifies the same application as the original trusted application object.

    Availability

    Available in OS X v10.2 and later.

  • Returns the CSSM CSP handle for the given keychain object.

    Declaration

    Objective-C

    OSStatus SecKeychainGetCSPHandle ( SecKeychainRef keychain, CSSM_CSP_HANDLE *cspHandle );

    Parameters

    keychain

    A keychain object.

    cspHandle

    On return, a pointer to the CSSM CSP handle for the given keychain. The handle is valid until the keychain object is released.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Returns the CSSM database handle for a given keychain object.

    Declaration

    Objective-C

    OSStatus SecKeychainGetDLDBHandle ( SecKeychainRef keychain, CSSM_DL_DB_HANDLE *dldbHandle );

    Parameters

    keychain

    A keychain object.

    dldbHandle

    On return, a pointer to the CSSM database handle for the given keychain. The handle is valid until the keychain object is released.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Returns the CSSM database handle for a given keychain item object.

    Declaration

    Objective-C

    OSStatus SecKeychainItemGetDLDBHandle ( SecKeychainItemRef keyItemRef, CSSM_DL_DB_HANDLE *dldbHandle );

    Parameters

    keyItemRef

    A keychain item object.

    dldbHandle

    On return, a pointer to a CSSM database handle for the keychain database containing the given item. The handle is valid until the keychain item object is released.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Returns a CSSM unique record for the given keychain item object.

    Declaration

    Objective-C

    OSStatus SecKeychainItemGetUniqueRecordID ( SecKeychainItemRef itemRef, const CSSM_DB_UNIQUE_RECORD * _Nullable *uniqueRecordID );

    Parameters

    itemRef

    A keychain item object.

    uniqueRecordID

    On return, a pointer to a CSSM unique record for the given item. The unique record is valid until the item object is released.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Availability

    Available in OS X v10.0 and later.

    Deprecated in OS X v10.7.

  • Registers your keychain event callback function

    Declaration

    Swift

    func SecKeychainAddCallback(_ callbackFunction: SecKeychainCallback, _ eventMask: SecKeychainEventMask, _ userContext: UnsafeMutablePointer<Void>) -> OSStatus

    Objective-C

    OSStatus SecKeychainAddCallback ( SecKeychainCallback callbackFunction, SecKeychainEventMask eventMask, void *userContext );

    Parameters

    callbackFunction

    A pointer to your keychain event callback function, described in SecKeychainCallback.

    eventMask

    A bit mask indicating the keychain events of which your application wishes to be notified. Keychain Services tests this mask to determine the keychain events that you wish to receive, and passes these events in the keychainEvent parameter of your callback function.

    userContext

    A pointer to application-defined storage that will be passed to your callback function. Your application can use this to associate any particular call of this function with any particular call of your keychain event callback function.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    It is important to note that the current Foundation or Core Foundation run loop must be active when making this call or the callbacks are not registered. In multithreaded programs, the notifications are registered in the run loop of the thread calling SecKeychainAddCallback; therefore, delivery of notifications depends on the functioning of that thread’s run loop. If that thread terminates, or is so busy that it doesn't operate its run loop in a timely manner, notifications will be delayed, and may eventually be dropped without any notification.

    For that reason, it is inadvisable for your program to depend on delivery of notifications caused by your own actions (such as depending on receiving a deletion notification before updating a UI view) unless your program is multithreaded and can take notifications on a thread different from the one generating the events.

    Availability

    Available in OS X v10.2 and later.

  • Unregisters your keychain event callback function.

    Declaration

    Swift

    func SecKeychainRemoveCallback(_ callbackFunction: SecKeychainCallback) -> OSStatus

    Objective-C

    OSStatus SecKeychainRemoveCallback ( SecKeychainCallback callbackFunction );

    Parameters

    callbackFunction

    The callback function pointer to remove.

    Return Value

    A result code. See Keychain Services Result Codes. Call SecCopyErrorMessageString (OS X only) to get a human-readable string explaining the result.

    Discussion

    Once removed, keychain events are not sent to the owner of the callback.

    Availability

    Available in OS X v10.2 and later.

Callbacks

Data Types

  • Identifies a keychain or keychain item’s access information.

    Declaration

    Swift

    class SecAccess { }

    Objective-C

    typedef struct OpaqueSecAccessRef *SecAccessRef;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Represents information about an access control list entry.

    Declaration

    Swift

    class SecACL { }

    Objective-C

    typedef struct OpaqueSecTrustRef *SecACLRef;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Represents a 16-byte Apple File Protocol server signature block.

    Declaration

    Swift

    typealias SecAFPServerSignature = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)

    Objective-C

    typedef UInt8 SecAFPServerSignature[16];

    Discussion

    This type represents a 16-byte Apple File Protocol server signature block. You can pass a value of this type in the serverSignature parameter of the functions KCAddAppleSharePassword and KCFindAppleSharePassword to represent an Apple File Protocol server signature. You can use a value of this type with the keychain item attribute constant kSecSignatureItemAttr to specify an Apple File Protocol server signature.

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Contains keychain attributes.

    Declaration

    Swift

    struct SecKeychainAttribute { var tag: SecKeychainAttrType var length: UInt32 var data: UnsafeMutablePointer<Void> }

    Objective-C

    struct SecKeychainAttribute { SecKeychainAttrType tag; UInt32 length; void *data; }; typedef struct SecKeychainAttribute SecKeychainAttribute;

    Fields

    tag

    A 4-byte attribute tag. See Keychain Item Attribute Constants for valid attribute types.

    length

    The length of the buffer pointed to by data.

    data

    A pointer to the attribute data.

    Availability

    Available in OS X v10.0 and later.

  • Represents a pointer to a keychain attribute structure.

    Declaration

    Swift

    typealias SecKeychainAttributePtr = UnsafeMutablePointer<SecKeychainAttribute>

    Objective-C

    typedef SecKeychainAttribute *SecKeychainAttributePtr;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.0 and later.

  • Represents an attribute.

    Declaration

    Swift

    struct SecKeychainAttributeInfo { var count: UInt32 var tag: UnsafeMutablePointer<UInt32> var format: UnsafeMutablePointer<UInt32> }

    Objective-C

    struct SecKeychainAttributeInfo { UInt32 count; UInt32 *tag; UInt32 *format; }; typedef struct SecKeychainAttributeInfo SecKeychainAttributeInfo;

    Fields

    count

    The number of tag-format pairs in the respective arrays.

    tag

    A pointer to the first attribute tag in the array.

    format

    A pointer to the first attribute format in the array. Attribute formats are of type CSSM_DB_ATTRIBUTE_FORMAT (CSSM_DB_ATTRIBUTE_FORMAT_STRING, for example), and are defined in the cssmtype.h header.

    Discussion

    Each tag and format item form a pair.

    Availability

    Available in OS X v10.2 and later.

  • Represents a list of keychain attributes.

    Declaration

    Swift

    struct SecKeychainAttributeList { var count: UInt32 var attr: UnsafeMutablePointer<SecKeychainAttribute> }

    Objective-C

    struct SecKeychainAttributeList { UInt32 count; SecKeychainAttribute *attr; }; typedef struct SecKeychainAttributeList SecKeychainAttributeList;

    Fields

    count

    An unsigned 32-bit integer that represents the number of keychain attributes in the array.

    attr

    A pointer to the first keychain attribute in the array.

    Availability

    Available in OS X v10.0 and later.

  • Represents a keychain attribute type.

    Declaration

    Swift

    typealias SecKeychainAttrType = OSType

    Objective-C

    typedef OSType SecKeychainAttrType;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.0 and later.

  • Contains information about a keychain event.

    Declaration

    Swift

    struct SecKeychainCallbackInfo { var version: UInt32 var item: Unmanaged<SecKeychainItem> var keychain: Unmanaged<SecKeychain> var pid: pid_t }

    Objective-C

    struct SecKeychainCallbackInfo { UInt32 version; SecKeychainItemRef item; SecKeychainRef keychain; pid_t pid; }; typedef struct SecKeychainCallbackInfo SecKeychainCallbackInfo;

    Fields

    version

    The version of this structure. See Keychain Settings Version for valid constants.

    item

    A reference to the keychain item in which the event occurred. If the event did not involve an item, this field is not valid.

    keychain

    A reference to the keychain in which the event occurred. If the event did not involve a keychain, this field is not valid.

    pid

    The ID of the process that generated this event.

    Discussion

    This structure contains information about the keychain event of which your application wants to be notified. Keychain Services passes a pointer to this structure in the info parameter of your callback function. For information on how to write a keychain event callback function, see SecKeychainCallback.

    Availability

    Available in OS X v10.2 and later.

  • Contains information about a keychain item.

    Declaration

    Swift

    class SecKeychainItem { }

    Objective-C

    typedef struct OpaqueSecKeychainItemRef *SecKeychainItemRef;

    Discussion

    A SecKeychainItemRef object for a certificate that is stored in a keychain can be safely cast to a SecCertificateRef for use with the Certificate, Key, and Trust API.

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.0 and later.

  • Contains information about a keychain.

    Declaration

    Swift

    class SecKeychain { }

    Objective-C

    typedef struct OpaqueSecKeychainRef *SecKeychainRef;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.0 and later.

  • Contains information about a keychain search.

    Declaration

    Swift

    class SecKeychainSearch { }

    Objective-C

    typedef struct OpaqueSecKeychainSearchRef *SecKeychainSearchRef;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.0 and later.

  • Contains information about keychain settings.

    Declaration

    Swift

    struct SecKeychainSettings { var version: UInt32 var lockOnSleep: DarwinBoolean var useLockInterval: DarwinBoolean var lockInterval: UInt32 init() init(version version: UInt32, lockOnSleep lockOnSleep: DarwinBoolean, useLockInterval useLockInterval: DarwinBoolean, lockInterval lockInterval: UInt32) }

    Objective-C

    struct SecKeychainSettings { UInt32 version; Boolean lockOnSleep; Boolean useLockInterval; UInt32 lockInterval; }; typedef struct SecKeychainSettings SecKeychainSettings;

    Fields

    version

    An unsigned 32-bit integer representing the keychain version.

    lockOnSleep

    A Boolean value indicating whether the keychain locks when the system sleeps.

    useLockInterval

    A Boolean value indicating whether the keychain automatically locks after a certain period of time.

    lockInterval

    An unsigned 32-bit integer representing the number of seconds before the keychain locks. If you set useLockInterval to FALSE, set lockInterval to INT_MAX to indicate that the keychain never locks.

    Discussion

    This structure contains information about a keychain’s settings such as locking on sleep and the lock time interval. You can use the SecKeychainSetSettings and SecKeychainCopySettings functions to set and copy a keychain’s settings.

    Availability

    Available in OS X v10.2 and later.

  • Contains input parameters for import and export functions.

    Declaration

    Swift

    struct SecKeyImportExportParameters { var version: UInt32 var flags: SecKeyImportExportFlags var passphrase: Unmanaged<AnyObject> var alertTitle: Unmanaged<CFString> var alertPrompt: Unmanaged<CFString> var accessRef: Unmanaged<SecAccess>? var keyUsage: CSSM_KEYUSE var keyAttributes: CSSM_KEYATTR_FLAGS }

    Objective-C

    typedef struct { /* for import and export */ uint32_t version; SecKeyImportExportFlags flags; CFTypeRef passphrase; CFStringRef alertTitle; CFStringRef alertPrompt; /* for import only */ SecAccessRef accessRef; CSSM_KEYUSE keyUsage; CSSM_KEYATTR_FLAGS keyAttributes; } SecKeyImportExportParameters;

    Fields

    version

    The version of this structure; the current value is SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION.

    flags

    A set of flag bits, defined in Keychain Item Import/Export Parameter Flags.

    passphrase

    A password, used for kSecFormatPKCS12 and kSecFormatWrapped formats only. (A password is sometimes referred to as a passphrase to emphasize the fact that a longer string that includes non-letter characters, such as numbers, punctuation, and spaces, is more secure than a simple word.) Legal types are CFStringRef and CFDataRef. PKCS12 requires passwords to be in Unicode format; passing in a CFStringRef as the password is the safest way to ensure that this requirement is met (and that the result is compatible with other implementations). If a CFDataRef object is supplied as the password for a PKCS12 export operation, the data is assumed to be in UTF8 form and is converted as appropriate.

    When importing or exporting keys (SecKeyRef objects) in one of the wrapped formats (kSecFormatWrappedOpenSSL, kSecFormatWrappedSSH, or kSecFormatWrappedPKCS8) or in PKCS12 format, you must either explicitly specify the passphrase field or set the kSecKeySecurePassphrase bit in the Flags field (to prompt the user for the password).

    alertTitle

    Title of secure password alert panel. When importing or exporting a key, if you set the kSecKeySecurePassphrase flag bit, you can optionally use this field to specify a string for the password panel’s title bar.

    alertPrompt

    Prompt in secure password alert panel. When importing or exporting a key, if you set the kSecKeySecurePassphrase flag bit, you can optionally use this field to specify a string for the prompt that appears in the password panel.

    accessRef

    Specifies the initial access controls of imported private keys. If more than one private key is being imported, all private keys get the same initial access controls. If this field is NULL when private keys are being imported, then the access object for the keychain item for an imported private key depends on the kSecKeyNoAccessControl bit in the flags parameter. If this bit is 0 (or keyParams is NULL), the default access control is used. If this bit is 1, no access object is attached to the keychain item for imported private keys.

    keyUsage

    A word of bits constituting the low-level use flags for imported keys as defined in cssmtype.h. If this field is 0 or keyParams is NULL, the default value is CSSM_KEYUSE_ANY.

    keyAttributes

    A word of bits constituting the low-level attribute flags for imported keys. The default value is CSSM_KEYATTR_SENSITIVE | CSSM_KEYATTR_EXTRACTABLE; the CSSM_KEYATTR_PERMANENT bit is also added to the default if a non-NULL value is specified for the importKeychain parameter.

    The following are valid values for these flags: CSSM_KEYATTR_PERMANENT, CSSM_KEYATTR_SENSITIVE, and CSSM_KEYATTR_EXTRACTABLE.

    If the CSSM_KEYATTR_PERMANENT bit is set, the importKeychain parameter is not valid, and if any keys are found in the external representation, then the error errSecInvalidKeychain is returned.

    The CSSM_KEYATTR_SENSITIVE bit indicates that the key can only be extracted in wrapped form.

    Important: If you do not set the CSSM_KEYATTR_EXTRACTABLE bit, you cannot extract the imported key from the keychain in any form, including in wrapped form.

    The CSSM_KEYATTR_FLAGS enumeration is defined in cssmtype.h. Note that the CSSM_KEYATTR_RETURN_xxx bits are always forced to CSSM_KEYATTR_RETURN_REF regardless of how they are specified in the keyAttributes field.

    Discussion

    This structure is passed in the keyParams parameter as input to the functions SecKeychainItemExport and SecKeychainItemImport.

    PKCS12 is an abbreviation for Public-Key Cryptography Standard # 12. This standard, by RSA Security, provides a format for external representation of keys and certificates and is described in PKCS 12 v1.0: Personal Information Exchange Syntax.

    Availability

    Available in OS X v10.4 and later.

  • A parameter block used for SecItemImport and SecItemExport.

    Declaration

    Swift

    struct SecItemImportExportKeyParameters { var version: UInt32 var flags: SecKeyImportExportFlags var passphrase: Unmanaged<AnyObject> var alertTitle: Unmanaged<CFString> var alertPrompt: Unmanaged<CFString> var accessRef: Unmanaged<SecAccess>? var keyUsage: Unmanaged<CFArray>? var keyAttributes: Unmanaged<CFArray>? }

    Objective-C

    typedef struct { /* for import and export */ uint32_t version; SecKeyImportExportFlags flags; CFTypeRef passphrase; CFStringRef alertTitle; CFStringRef alertPrompt; /* for import only */ SecAccessRef accessRef; CFArrayRef keyUsage; CFArrayRef keyAttributes; } SecItemImportExportKeyParameters;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.7 and later.

  • Contains information about a trusted application.

    Declaration

    Swift

    class SecTrustedApplication { }

    Objective-C

    typedef struct OpaqueSecTrustedApplicationRef *SecTrustedApplicationRef;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Contains information about a password.

    Declaration

    Swift

    class SecPassword { }

    Objective-C

    typedef struct OpaqueSecPasswordRef *SecPasswordRef;

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.4 and later.

Constants

OS X Keychain Services API Constants

  • Defines the version of an import/export parameters structure.

    Declaration

    Swift

    var SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION: Int32 { get }

    Objective-C

    #define SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION 0

    Constants

    • SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION

      SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION

      Defines the version number for a SecImportExportParameters structure used as input to the functions SecKeychainItemExport and SecKeychainItemImport.

      Available in OS X v10.4 and later.

  • Defines constants you can use to identify the type of authentication to use for an Internet password.

    Declaration

    Swift

    enum SecAuthenticationType : FourCharCode { case NTLM case MSN case DPA case RPA case HTTPBasic case HTTPDigest case HTMLForm case Default case Any }

    Objective-C

    typedef FourCharCode SecAuthenticationType; enum { kSecAuthenticationTypeNTLM = AUTH_TYPE_FIX_ ('ntlm'), kSecAuthenticationTypeMSN = AUTH_TYPE_FIX_ ('msna'), kSecAuthenticationTypeDPA = AUTH_TYPE_FIX_ ('dpaa'), kSecAuthenticationTypeRPA = AUTH_TYPE_FIX_ ('rpaa'), kSecAuthenticationTypeHTTPBasic = AUTH_TYPE_FIX_ ('http'), kSecAuthenticationTypeHTTPDigest = AUTH_TYPE_FIX_ ('httd'), kSecAuthenticationTypeHTMLForm = AUTH_TYPE_FIX_ ('form'), kSecAuthenticationTypeDefault = AUTH_TYPE_FIX_ ('dflt'), kSecAuthenticationTypeAny = AUTH_TYPE_FIX_ ( 0 ) };

    Constants

    • NTLM

      kSecAuthenticationTypeNTLM

      Specifies Windows NT LAN Manager authentication.

      Available in OS X v10.2 and later.

    • MSN

      kSecAuthenticationTypeMSN

      Specifies Microsoft Network default authentication.

      Available in OS X v10.2 and later.

    • DPA

      kSecAuthenticationTypeDPA

      Specifies Distributed Password authentication.

      Available in OS X v10.2 and later.

    • RPA

      kSecAuthenticationTypeRPA

      Specifies Remote Password authentication.

      Available in OS X v10.2 and later.

    • HTTPBasic

      kSecAuthenticationTypeHTTPBasic

      Specifies HTTP Basic authentication.

      Available in OS X v10.3 and later.

    • HTTPDigest

      kSecAuthenticationTypeHTTPDigest

      Specifies HTTP Digest Access authentication.

      Available in OS X v10.2 and later.

    • HTMLForm

      kSecAuthenticationTypeHTMLForm

      Specifies HTML form based authentication.

      Available in OS X v10.3 and later.

    • Default

      kSecAuthenticationTypeDefault

      Specifies the default authentication type.

      Available in OS X v10.2 and later.

    • Any

      kSecAuthenticationTypeAny

      Specifies that any authentication type is acceptable.

      When performing a search, use this value to avoid constraining your search results to a particular authentication type.

      Available in OS X v10.5 and later.

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Defines the keychain-related event.

    Declaration

    Swift

    enum SecKeychainEvent : UInt32 { case LockEvent case UnlockEvent case AddEvent case DeleteEvent case UpdateEvent case PasswordChangedEvent case DefaultChangedEvent case DataAccessEvent case KeychainListChangedEvent case TrustSettingsChangedEvent }

    Objective-C

    typedef UInt32 SecKeychainEvent; enum { kSecLockEvent = 1, kSecUnlockEvent = 2, kSecAddEvent = 3, kSecDeleteEvent = 4, kSecUpdateEvent = 5, kSecPasswordChangedEvent = 6, kSecDefaultChangedEvent = 9, kSecDataAccessEvent = 10, kSecKeychainListChangedEvent = 11, kSecTrustSettingsChangedEvent = 12 };

    Constants

    • LockEvent

      kSecLockEvent

      Indicates a keychain was locked.

      It is impossible to distinguish between a lock event caused by an explicit request and one caused by a keychain that locked itself because of a timeout. Therefore, the pid parameter in the SecKeychainCallbackInfo structure does not contain useful information for this event. Note that when the login session terminates, all keychains become effectively locked; however, no kSecLockEvent events are generated in this case.

      Available in OS X v10.2 and later.

    • UnlockEvent

      kSecUnlockEvent

      Indicates a keychain was successfully unlocked.

      It is impossible to distinguish between an unlock event caused by an explicit request and one that occurred automatically because the keychain was needed to perform an operation. In either case, however, the pid parameter in the SecKeychainCallbackInfo structure does return the ID of the process whose actions caused the unlock event.

      Available in OS X v10.2 and later.

    • AddEvent

      kSecAddEvent

      Indicates an item was added to a keychain.

      Available in OS X v10.2 and later.

    • DeleteEvent

      kSecDeleteEvent

      Indicates an item was deleted from a keychain.

      Available in OS X v10.2 and later.

    • UpdateEvent

      kSecUpdateEvent

      Indicates a keychain item was updated.

      Available in OS X v10.2 and later.

    • PasswordChangedEvent

      kSecPasswordChangedEvent

      Indicates the keychain password was changed.

      Available in OS X v10.2 and later.

    • DefaultChangedEvent

      kSecDefaultChangedEvent

      Indicates that a different keychain was specified as the default.

      Available in OS X v10.2 and later.

    • DataAccessEvent

      kSecDataAccessEvent

      Indicates a process has accessed a keychain item’s data.

      Available in OS X v10.2 and later.

    • KeychainListChangedEvent

      kSecKeychainListChangedEvent

      Indicates the list of keychains has changed.

      Available in OS X v10.2 and later.

    • TrustSettingsChangedEvent

      kSecTrustSettingsChangedEvent

      Indicates trust settings have changed.

      Available in OS X v10.5 and later.

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Defines bit masks for keychain event constants

    Declaration

    Swift

    struct SecKeychainEventMask : OptionSetType { init(rawValue rawValue: UInt32) static var LockEventMask: SecKeychainEventMask { get } static var UnlockEventMask: SecKeychainEventMask { get } static var AddEventMask: SecKeychainEventMask { get } static var DeleteEventMask: SecKeychainEventMask { get } static var UpdateEventMask: SecKeychainEventMask { get } static var PasswordChangedEventMask: SecKeychainEventMask { get } static var DefaultChangedEventMask: SecKeychainEventMask { get } static var DataAccessEventMask: SecKeychainEventMask { get } static var KeychainListChangedMask: SecKeychainEventMask { get } static var TrustSettingsChangedEventMask: SecKeychainEventMask { get } static var EveryEventMask: SecKeychainEventMask { get } }

    Objective-C

    typedef UInt32 SecKeychainEventMask; enum { kSecLockEventMask = 1 << kSecLockEvent, kSecUnlockEventMask = 1 << kSecUnlockEvent, kSecAddEventMask = 1 << kSecAddEvent, kSecDeleteEventMask = 1 << kSecDeleteEvent, kSecUpdateEventMask = 1 << kSecUpdateEvent, kSecPasswordChangedEventMask = 1 << kSecPasswordChangedEvent, kSecDefaultChangedEventMask = 1 << kSecDefaultChangedEvent, kSecDataAccessEventMask = 1 << kSecDataAccessEvent, kSecKeychainListChangedMask = 1 << kSecKeychainListChangedEvent, kSecTrustSettingsChangedEventMask = 1 << kSecTrustSettingsChangedEvent, kSecEveryEventMask = 0xffffffff };

    Constants

    • LockEventMask

      kSecLockEventMask

      If the bit specified by this mask is set, your callback function is invoked when a keychain is locked.

      Available in OS X v10.2 and later.

    • UnlockEventMask

      kSecUnlockEventMask

      If the bit specified by this mask is set, your callback function is invoked when a keychain is unlocked.

      Available in OS X v10.2 and later.

    • AddEventMask

      kSecAddEventMask

      If the bit specified by this mask is set, your callback function is invoked when an item is added to a keychain.

      Available in OS X v10.2 and later.

    • DeleteEventMask

      kSecDeleteEventMask

      If the bit specified by this mask is set, your callback function is invoked when an item is deleted from a keychain.

      Available in OS X v10.2 and later.

    • UpdateEventMask

      kSecUpdateEventMask

      If the bit specified by this mask is set, your callback function is invoked when a keychain item is updated.

      Available in OS X v10.2 and later.

    • PasswordChangedEventMask

      kSecPasswordChangedEventMask

      If the bit specified by this mask is set, your callback function is invoked when the keychain password is changed.

      Available in OS X v10.2 and later.

    • DefaultChangedEventMask

      kSecDefaultChangedEventMask

      If the bit specified by this mask is set, your callback function is invoked when a different keychain is specified as the default.

      Available in OS X v10.2 and later.

    • DataAccessEventMask

      kSecDataAccessEventMask

      If the bit specified by this mask is set, your callback function is invoked when a process accesses a keychain item’s data.

      Available in OS X v10.2 and later.

    • KeychainListChangedMask

      kSecKeychainListChangedMask

      If the bit specified by this mask is set, your callback function is invoked when a keychain list is changed.

      Available in OS X v10.2 and later.

    • TrustSettingsChangedEventMask

      kSecTrustSettingsChangedEventMask

      If the bit specified by this mask is set, your callback function is invoked when there is a change in certificate trust settings.

      Available in OS X v10.5 and later.

    • EveryEventMask

      kSecEveryEventMask

      If all the bits are set, your callback function is invoked whenever any event occurs.

      Available in OS X v10.2 and later.

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Specifies a keychain item’s attributes.

    Declaration

    Swift

    enum SecItemAttr : FourCharCode { case CreationDateItemAttr case ModDateItemAttr case DescriptionItemAttr case CommentItemAttr case CreatorItemAttr case TypeItemAttr case ScriptCodeItemAttr case LabelItemAttr case InvisibleItemAttr case NegativeItemAttr case CustomIconItemAttr case AccountItemAttr case ServiceItemAttr case GenericItemAttr case SecurityDomainItemAttr case ServerItemAttr case AuthenticationTypeItemAttr case PortItemAttr case PathItemAttr case VolumeItemAttr case AddressItemAttr case SignatureItemAttr case ProtocolItemAttr case CertificateType case CertificateEncoding case CrlType case CrlEncoding case Alias }

    Objective-C

    typedef FourCharCode SecItemAttr; enum { kSecCreationDateItemAttr = 'cdat', kSecModDateItemAttr = 'mdat', kSecDescriptionItemAttr = 'desc', kSecCommentItemAttr = 'icmt', kSecCreatorItemAttr = 'crtr', kSecTypeItemAttr = 'type', kSecScriptCodeItemAttr = 'scrp', kSecLabelItemAttr = 'labl', kSecInvisibleItemAttr = 'invi', kSecNegativeItemAttr = 'nega', kSecCustomIconItemAttr = 'cusi', kSecAccountItemAttr = 'acct', kSecServiceItemAttr = 'svce', kSecGenericItemAttr = 'gena', kSecSecurityDomainItemAttr = 'sdmn', kSecServerItemAttr = 'srvr', kSecAuthenticationTypeItemAttr = 'atyp', kSecPortItemAttr = 'port', kSecPathItemAttr = 'path', kSecVolumeItemAttr = 'vlme', kSecAddressItemAttr = 'addr', kSecSignatureItemAttr = 'ssig', kSecProtocolItemAttr = 'ptcl', kSecCertificateType = 'ctyp', kSecCertificateEncoding = 'cenc', kSecCrlType = 'crtp', kSecCrlEncoding = 'crnc', kSecAlias = 'alis' };

    Constants

    • CreationDateItemAttr

      kSecCreationDateItemAttr

      Identifies the creation date attribute.

      You use this tag to get a string value that represents the date the item was created, expressed in Zulu Time format ("YYYYMMDDhhmmssZ"). This is the native format for stored time values in the CDSA specification (defined as CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE in the CSSM_DB_ATTRIBUTE_FORMAT enumeration, Section 17.2.6.). When specifying the creation date as input to a function (for example, SecKeychainSearchCreateFromAttributes), you may alternatively provide a numeric value of type UInt32 or SInt64, expressed as seconds since 01 January 1904.

      Available in OS X v10.2 and later.

    • ModDateItemAttr

      kSecModDateItemAttr

      Identifies the modification date attribute.

      You use this tag to get a string value that represents the date the item was created, expressed in Zulu Time format ("YYYYMMDDhhmmssZ"). This is the native format for stored time values in the CDSA specification (defined as CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE in the CSSM_DB_ATTRIBUTE_FORMAT enumeration, Section 17.2.6.). When specifying the creation date as input to a function (for example, SecKeychainSearchCreateFromAttributes), you may alternatively provide a numeric value of type UInt32 or SInt64, expressed as seconds since 01 January 1904.

      Available in OS X v10.2 and later.

    • DescriptionItemAttr

      kSecDescriptionItemAttr

      Identifies the description attribute.

      You use this tag to set or get a string value that represents a user-visible string describing this particular kind of item, for example “disk image password”. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • CommentItemAttr

      kSecCommentItemAttr

      Identifies the comment attribute.

      You use this tag to set or get a string value that represents a user-editable string containing comments for this item. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • CreatorItemAttr

      kSecCreatorItemAttr

      Identifies the creator attribute.

      You use this tag to set or get a value of type FourCharCode that represents the item's creator.

      Available in OS X v10.2 and later.

    • TypeItemAttr

      kSecTypeItemAttr

      Identifies the type attribute.

      You use this tag to set or get a value of type FourCharCode that represents the item’s type.

      Available in OS X v10.2 and later.

    • ScriptCodeItemAttr

      kSecScriptCodeItemAttr

      Identifies the script code attribute.

      You use this tag to set or get a value of type ScriptCode that represents the script code for all strings. Use of this attribute is deprecated; string attributes should always be stored in UTF-8 encoding.

      Available in OS X v10.2 and later.

    • LabelItemAttr

      kSecLabelItemAttr

      Identifies the label attribute.

      You use this tag to set or get a string value that represents a user-editable string containing the label for this item. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • InvisibleItemAttr

      kSecInvisibleItemAttr

      Identifies the invisible attribute.

      You use this tag to set or get a value of type Boolean that indicates whether the item is invisible (that is, should not be displayed).

      Available in OS X v10.2 and later.

    • NegativeItemAttr

      kSecNegativeItemAttr

      Identifies the negative attribute.

      You use this tag to set or get a value of type Boolean that indicates whether there is a valid password associated with this keychain item. This is useful if your application doesn’t want a password for some particular service to be stored in the keychain, but prefers that it always be entered by the user. The item, which is typically invisible and with zero-length data, acts as a placeholder.

      Available in OS X v10.2 and later.

    • CustomIconItemAttr

      kSecCustomIconItemAttr

      Identifies the custom icon attribute.

      Use of this attribute is deprecated. Custom icons for keychains are not supported in OS X.

      Available in OS X v10.2 and later.

    • AccountItemAttr

      kSecAccountItemAttr

      Identifies the account attribute.

      You use this tag to set or get a string that represents the user account. It also applies to generic, Internet, and AppleShare password items. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • ServiceItemAttr

      kSecServiceItemAttr

      Identifies the service attribute.

      You use this tag to set or get a string that represents the service associated with this item, for example, “iTools”. This is unique to generic password attributes. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • GenericItemAttr

      kSecGenericItemAttr

      Identifies the generic attribute.

      You use this tag to set or get a value of untyped bytes that represents a user-defined attribute. This is unique to generic password attributes.

      Available in OS X v10.2 and later.

    • SecurityDomainItemAttr

      kSecSecurityDomainItemAttr

      Identifies the security domain attribute.

      You use this tag to set or get a value that represents the Internet security domain. This is unique to Internet password attributes.

      Available in OS X v10.2 and later.

    • ServerItemAttr

      kSecServerItemAttr

      Identifies the server attribute.

      You use this tag to set or get a string that represents the Internet server’s domain name or IP address. This is unique to Internet password attributes. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • AuthenticationTypeItemAttr

      kSecAuthenticationTypeItemAttr

      Identifies the authentication type attribute.

      You use this tag to set or get a value of type SecAuthenticationType that represents the Internet authentication scheme. For possible authentication values, see Keychain Authentication Type Constants. This is unique to Internet password attributes.

      Available in OS X v10.2 and later.

    • PortItemAttr

      kSecPortItemAttr

      Identifies the port attribute.

      You use this tag to set or get a value of type UInt32 that represents the Internet port number. This is unique to Internet password attributes.

      Available in OS X v10.2 and later.

    • PathItemAttr

      kSecPathItemAttr

      Identifies the path attribute.

      You use this tag to set or get a string value that represents the path. This is unique to Internet password attributes. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • VolumeItemAttr

      kSecVolumeItemAttr

      Identifies the volume attribute.

      You use this tag to set or get a string value that represents the AppleShare volume. This is unique to AppleShare password attributes. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • AddressItemAttr

      kSecAddressItemAttr

      Identifies the address attribute.

      You use this tag to set or get a value of type string that represents the AppleTalk zone name, or the IP or domain name that represents the server address. This is unique to AppleShare password attributes. Keychain strings should use UTF-8 encoding.

      Available in OS X v10.2 and later.

    • SignatureItemAttr

      kSecSignatureItemAttr

      Identifies the server signature attribute.

      You use this tag to set or get a value of type SecAFPServerSignature that represents the server signature block. This is unique to AppleShare password attributes.

      Available in OS X v10.2 and later.

    • ProtocolItemAttr

      kSecProtocolItemAttr

      Identifies the protocol attribute.

      You use this tag to set or get a value of type SecProtocolType that represents the Internet protocol. For possible protocol type values, see Keychain Protocol Type Constants. This is unique to AppleShare and Internet password attributes.

      Available in OS X v10.2 and later.

    • CertificateType

      kSecCertificateType

      Indicates a CSSM_CERT_TYPE type.

      Available in OS X v10.2 and later.

    • CertificateEncoding

      kSecCertificateEncoding

      Indicates a CSSM_CERT_ENCODING type.

      Available in OS X v10.2 and later.

    • CrlType

      kSecCrlType

      Indicates a CSSM_CRL_TYPE type.

      Available in OS X v10.2 and later.

    • CrlEncoding

      kSecCrlEncoding

      Indicates a CSSM_CRL_ENCODING type.

      Available in OS X v10.2 and later.

    • Alias

      kSecAlias

      Indicates an alias.

      Available in OS X v10.2 and later.

    Discussion

    Not all of these attributes are used for all types of items. Which set of attributes exist for each type of item is documented in the “Data Storage Library Services” chapter of Common Security: CDSA and CSSM, version 2 (with corrigenda) from The Open Group (http://www.opengroup.org/security/cdsa.htm) for standard items and in the DL section of the Security Release Notes for Apple-defined item types (if any).

    To obtain information about a certificate, use the CDSA Certificate Library (CL) API. To obtain information about a key, use the SecKeyGetCSSMKey function and the CDSA Cryptographic Service Provider (CSP) API.

    For attributes for keys, see Keychain Item Attribute Constants For Keys.

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Specifies the attributes for a key item in a keychain.

    Declaration

    Swift

    var kSecKeyKeyClass: Int32 { get } var kSecKeyPrintName: Int32 { get } var kSecKeyAlias: Int32 { get } var kSecKeyPermanent: Int32 { get } var kSecKeyPrivate: Int32 { get } var kSecKeyModifiable: Int32 { get } var kSecKeyLabel: Int32 { get } var kSecKeyApplicationTag: Int32 { get } var kSecKeyKeyCreator: Int32 { get } var kSecKeyKeyType: Int32 { get } var kSecKeyKeySizeInBits: Int32 { get } var kSecKeyEffectiveKeySize: Int32 { get } var kSecKeyStartDate: Int32 { get } var kSecKeyEndDate: Int32 { get } var kSecKeySensitive: Int32 { get } var kSecKeyAlwaysSensitive: Int32 { get } var kSecKeyExtractable: Int32 { get } var kSecKeyNeverExtractable: Int32 { get } var kSecKeyEncrypt: Int32 { get } var kSecKeyDecrypt: Int32 { get } var kSecKeyDerive: Int32 { get } var kSecKeySign: Int32 { get } var kSecKeyVerify: Int32 { get } var kSecKeySignRecover: Int32 { get } var kSecKeyVerifyRecover: Int32 { get } var kSecKeyWrap: Int32 { get } var kSecKeyUnwrap: Int32 { get }

    Objective-C

    enum { kSecKeyKeyClass =0, kSecKeyPrintName =1, kSecKeyAlias =2, kSecKeyPermanent =3, kSecKeyPrivate =4, kSecKeyModifiable =5, kSecKeyLabel =6, kSecKeyApplicationTag =7, kSecKeyKeyCreator =8, kSecKeyKeyType =9, kSecKeyKeySizeInBits =10, kSecKeyEffectiveKeySize =11, kSecKeyStartDate =12, kSecKeyEndDate =13, kSecKeySensitive =14, kSecKeyAlwaysSensitive =15, kSecKeyExtractable =16, kSecKeyNeverExtractable =17, kSecKeyEncrypt =18, kSecKeyDecrypt =19, kSecKeyDerive =20, kSecKeySign =21, kSecKeyVerify =22, kSecKeySignRecover =23, kSecKeyVerifyRecover =24, kSecKeyWrap =25, kSecKeyUnwrap =26 };

    Constants

    • kSecKeyKeyClass

      kSecKeyKeyClass

      Type uint32 (CSSM_KEYCLASS); value is one of CSSM_KEYCLASS_PUBLIC_KEY, CSSM_KEYCLASS_PRIVATE_KEY or CSSM_KEYCLASS_SESSION_KEY.

      Available in OS X v10.4 and later.

    • kSecKeyPrintName

      kSecKeyPrintName

      Type blob; human readable name of the key. Same as kSecLabelItemAttr for normal keychain items.

      Available in OS X v10.4 and later.

    • kSecKeyAlias

      kSecKeyAlias

      Type blob; currently unused.

      Available in OS X v10.4 and later.

    • kSecKeyPermanent

      kSecKeyPermanent

      Type uint32; value is nonzero. This key is permanent (stored in some keychain) and is always 1.

      Available in OS X v10.4 and later.

    • kSecKeyPrivate

      kSecKeyPrivate

      Type uint32; value is nonzero. This key is protected by a user login, a password, or both.

      Available in OS X v10.4 and later.

    • kSecKeyModifiable

      kSecKeyModifiable

      Type uint32; value is nonzero. Attributes of this key can be modified.

      Available in OS X v10.4 and later.

    • kSecKeyLabel

      kSecKeyLabel

      Type blob; for private and public keys this contains the hash of the public key. This is used to associate certificates and keys. Its value matches the value of the kSecPublicKeyHashItemAttr attribute of a certificate and it's used to construct an identity from a certificate and a key. For symmetric keys this is whatever the creator of the key passed in when they generated the key.

      Available in OS X v10.4 and later.

    • kSecKeyApplicationTag

      kSecKeyApplicationTag

      Type blob; currently unused.

      Available in OS X v10.4 and later.

    • kSecKeyKeyCreator

      kSecKeyKeyCreator

      Type data. The data points to a CSSM_GUID structure representing the module ID of the CSP owning this key.

      Available in OS X v10.4 and later.

    • kSecKeyKeyType

      kSecKeyKeyType

      Type uint32; value is a CSSM algorithm (CSSM_ALGORITHMS) representing the algorithm associated with this key.

      Available in OS X v10.4 and later.

    • kSecKeyKeySizeInBits

      kSecKeyKeySizeInBits

      Type uint32; value is the number of bits in this key.

      Available in OS X v10.4 and later.

    • kSecKeyEffectiveKeySize

      kSecKeyEffectiveKeySize

      Type uint32; value is the effective number of bits in this key. For example, a DES key has a key size in bits (kSecKeyKeySizeInBits) of 64 but a value for kSecKeyEffectiveKeySize of 56.

      Available in OS X v10.4 and later.

    • kSecKeyStartDate

      kSecKeyStartDate

      Type CSSM_DATE. Earliest date at which this key may be used. If the value is all zeros or not present, no restriction applies.

      Available in OS X v10.4 and later.

    • kSecKeyEndDate

      kSecKeyEndDate

      Type CSSM_DATE. Latest date at which this key may be used. If the value is all zeros or not present, no restriction applies.

      Available in OS X v10.4 and later.

    • kSecKeySensitive

      kSecKeySensitive

      Type uint32; value is nonzero. This key cannot be wrapped with CSSM_ALGID_NONE.

      Available in OS X v10.4 and later.

    • kSecKeyAlwaysSensitive

      kSecKeyAlwaysSensitive

      Type uint32; value is nonzero. This key has always been marked sensitive.

      Available in OS X v10.4 and later.

    • kSecKeyExtractable

      kSecKeyExtractable

      Type uint32; value is nonzero. This key can be wrapped.

      Available in OS X v10.4 and later.

    • kSecKeyNeverExtractable

      kSecKeyNeverExtractable

      Type uint32; value is nonzero. This key was never marked extractable.

      Available in OS X v10.4 and later.

    • kSecKeyEncrypt

      kSecKeyEncrypt

      Type uint32; value is nonzero. This key can be used in an encrypt operation.

      Available in OS X v10.4 and later.

    • kSecKeyDecrypt

      kSecKeyDecrypt

      Type uint32; value is nonzero. This key can be used in a decrypt operation.

      Available in OS X v10.4 and later.

    • kSecKeyDerive

      kSecKeyDerive

      Type uint32; value is nonzero. This key can be used in a key derivation operation.

      Available in OS X v10.4 and later.

    • kSecKeySign

      kSecKeySign

      Type uint32, value is nonzero. This key can be used in a sign operation.

      Available in OS X v10.4 and later.

    • kSecKeyVerify

      kSecKeyVerify

      Type uint32, value is nonzero. This key can be used in a verify operation.

      Available in OS X v10.4 and later.

    • kSecKeySignRecover

      kSecKeySignRecover

      Type uint32.

      Available in OS X v10.4 and later.

    • kSecKeyVerifyRecover

      kSecKeyVerifyRecover

      Type uint32. This key can unwrap other keys.

      Available in OS X v10.4 and later.

    • kSecKeyWrap

      kSecKeyWrap

      Type uint32; value is nonzero. This key can wrap other keys.

      Available in OS X v10.4 and later.

    • kSecKeyUnwrap

      kSecKeyUnwrap

      Type uint32; value is nonzero. This key can unwrap other keys.

      Available in OS X v10.4 and later.

    Discussion

    For attributes for items other than keys, see Keychain Item Attribute Constants.

  • Specifies a keychain item’s class code.

    Declaration

    Swift

    enum SecItemClass : FourCharCode { case InternetPasswordItemClass case GenericPasswordItemClass case AppleSharePasswordItemClass case CertificateItemClass case PublicKeyItemClass case PrivateKeyItemClass case SymmetricKeyItemClass }

    Objective-C

    typedef FourCharCode SecItemClass; enum { /* SecKeychainItem.h */ kSecInternetPasswordItemClass = 'inet', kSecGenericPasswordItemClass = 'genp', kSecAppleSharePasswordItemClass = 'ashp', kSecCertificateItemClass = CSSM_DL_DB_RECORD_X509_CERTIFICATE, kSecPublicKeyItemClass = CSSM_DL_DB_RECORD_PUBLIC_KEY, kSecPrivateKeyItemClass = CSSM_DL_DB_RECORD_PRIVATE_KEY, kSecSymmetricKeyItemClass = CSSM_DL_DB_RECORD_SYMMETRIC_KEY }; enum { /* Record Type defined in The Open Group Application Name Space */ /* cssmtype.h */ CSSM_DL_DB_RECORD_ALL_KEYS = CSSM_DB_RECORDTYPE_OPEN_GROUP_START + 8 };

    Constants

    • InternetPasswordItemClass

      kSecInternetPasswordItemClass

      Indicates that the item is an Internet password.

      Available in OS X v10.2 and later.

    • GenericPasswordItemClass

      kSecGenericPasswordItemClass

      Indicates that the item is a generic password.

      Available in OS X v10.2 and later.

    • kSecAppleSharePasswordItemClass

      Indicates that the item is an AppleShare password.

      Available in OS X v10.0 and later.

      Deprecated in OS X v10.9.

    • CertificateItemClass

      kSecCertificateItemClass

      Indicates that the item is an X509 certificate.

      Available in OS X v10.2 and later.

    • PublicKeyItemClass

      kSecPublicKeyItemClass

      Indicates that the item is a public key of a public-private pair.

      Available in OS X v10.5 and later.

    • PrivateKeyItemClass

      kSecPrivateKeyItemClass

      Indicates that the item is a private key of a public-private pair.

      Available in OS X v10.5 and later.

    • SymmetricKeyItemClass

      kSecSymmetricKeyItemClass

      Indicates that the item is a private key used for symmetric-key encryption.

      Available in OS X v10.5 and later.

    • CSSM_DL_DB_RECORD_ALL_KEYS

      CSSM_DL_DB_RECORD_ALL_KEYS

      The item can be any type of key; used for searches only.

      Available in OS X v10.0 and later.

    Discussion

    These enumerations define constants your application can use to specify the type of the keychain item you wish to create, dispose, add, delete, update, copy, or locate. You can also use these constants with the tag constant SecItemAttr.

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.2 and later.

  • Defines values for import and export flags.

    Declaration

    Swift

    struct SecItemImportExportFlags : OptionSetType { init(rawValue rawValue: UInt32) static var PemArmour: SecItemImportExportFlags { get } }

    Objective-C

    enum { kSecItemPemArmour = 0x00000001, }; typedef uint32_t SecItemImportExportFlags;

    Constants

    • PemArmour

      kSecItemPemArmour

      The exported data should have PEM armor.

      Available in OS X v10.4 and later.

    Discussion

    This enumeration lists values used by the flags parameter of the functions SecKeychainItemExport and SecKeychainItemImport.

    PEM armor refers to a way of expressing binary data as an ASCII string so that it can be transferred over text-only channels such as email. (PEM stands for an Internet standard, Privacy Enhanced Mail.)

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.4 and later.

  • Defines values for the flags field of the import/export parameters.

    Declaration

    Swift

    struct SecKeyImportExportFlags : OptionSetType { init(rawValue rawValue: UInt32) static var ImportOnlyOne: SecKeyImportExportFlags { get } static var SecurePassphrase: SecKeyImportExportFlags { get } static var NoAccessControl: SecKeyImportExportFlags { get } }

    Objective-C

    enum { kSecKeyImportOnlyOne = 0x00000001, kSecKeySecurePassphrase = 0x00000002, kSecKeyNoAccessControl = 0x00000004 }; typedef uint32_t SecKeyImportExportFlags;

    Constants

    • ImportOnlyOne

      kSecKeyImportOnlyOne

      Prevents the importing of more than one private key by the SecKeychainItemImport function. If the importKeychain parameter is NULL, this bit is ignored. Otherwise, if this bit is set and there is more than one key in the incoming external representation, no items are imported to the specified keychain and the error errSecMultipleKeys is returned.

      Available in OS X v10.4 and later.

    • SecurePassphrase

      kSecKeySecurePassphrase

      When set, the password for import or export is obtained by user prompt. (A password is sometimes referred to as a passphrase to emphasize the fact that a longer string that includes non-letter characters, such as numbers, punctuation, and spaces, is more secure than a simple word.) Otherwise, you must provide the password in the passphrase field of the SecKeyImportExportParameters structure. A user-supplied password is preferred, because it avoids having the cleartext password appear in the application’s address space at any time.

      Available in OS X v10.4 and later.

    • NoAccessControl

      kSecKeyNoAccessControl

      When set, imported private keys have no access object attached to them. In the absence of both this bit and the accessRef field in SecKeyImportExportParameters, imported private keys are given default access controls.

      Available in OS X v10.4 and later.

    Discussion

    These flags are used as input to the import/export parameters structure (SecKeyImportExportParameters, which in turn is used as input to the functions SecKeychainItemExport and SecKeychainItemImport.

    Import Statement

    Objective-C

    @import Security;

    Swift

    import Security

    Availability

    Available in OS X v10.4 and later.

  • Specifies the format of an item after export from or before import to the keychain.

    Declaration

    Swift

    enum SecExternalFormat : UInt32 { case FormatUnknown case FormatOpenSSL case FormatSSH case FormatBSAFE case FormatRawKey case FormatWrappedPKCS8 case FormatWrappedOpenSSL case FormatWrappedSSH case FormatWrappedLSH case FormatX509Cert case FormatPEMSequence case FormatPKCS7 case FormatPKCS12 case FormatNetscapeCertSequence case FormatSSHv2 }

    Objective-C

    enum { kSecFormatUnknown = 0, /* Asymmetric Key Formats */ kSecFormatOpenSSL, kSecFormatSSH, kSecFormatBSAFE, kSecFormatSSHv2</