Class

# Keychain

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Description

Gives you access to the default macOS Keychains for your applications. It is a macOS-only feature. The <span class="title-ref">Keychain</span> class does not provide access to internet passwords.

## Properties

<div class="rst-class">

table-centered_columns_3_and_4

</div>

| Name                      | Type                               | Read-Only | Shared |
|---------------------------|------------------------------------|-----------|--------|
| `Handle<keychain.handle>` | `Integer</api/data_types/integer>` | ✓         |        |

## Methods

<div class="rst-class">

table-centered_column_4

</div>

| Name                                  | Parameters                                                                                                                                                                               | Returns                          | Shared |
|---------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------|--------|
| `AddPassword<keychain.addpassword>`   | KCItem As `KeychainItem</api/macos/keychainitem>`, Password As `String</api/data_types/string>`, `Optional</api/language/optional>` Synced As `Boolean</api/data_types/boolean>` = False |                                  |        |
| `Constructor<keychain.constructor0>`  | Index As `Integer</api/data_types/integer>`                                                                                                                                              |                                  |        |
| `FindPassword<keychain.findpassword>` | `ByRef</api/language/byref>` KCItem As `KeychainItem</api/macos/keychainitem>`, `Optional</api/language/optional>` Synced As `Boolean</api/data_types/boolean>` = False                  | `String</api/data_types/string>` |        |
| `Lock<keychain.lock>`                 | LockAll As `Boolean</api/data_types/boolean>`                                                                                                                                            |                                  |        |
| `Unlock<keychain.unlock>`             | Password As `String</api/data_types/string>`                                                                                                                                             |                                  |        |

## Property descriptions

<div id="keychain.handle">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Keychain.Handle

**Handle** As `Integer</api/data_types/integer>`

> Returns a Handle to the <span class="title-ref">Keychain</span>. Useful only if you want to refer to Keychains with `Declare</api/language/declare>` statements.
>
> This property is read-only.

## Method descriptions

<div id="keychain.addpassword">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Keychain.AddPassword

**AddPassword**(KCItem As `KeychainItem</api/macos/keychainitem>`, Password As `String</api/data_types/string>`, `Optional</api/language/optional>` Synced As `Boolean</api/data_types/boolean>` = False)

> Adds the *Password* to the <span class="title-ref">Keychain</span> and associates it with a `KeychainItem</api/macos/keychainitem>`. If it fails, it generates a `KeychainException</api/exceptions/keychainexception>`.
>
> When *Synced* is `True</api/language/true>`, the password is added to the iCloud <span class="title-ref">Keychain</span> instead of the local <span class="title-ref">Keychain</span>. See the Notes section for additional requirements when working with iCloud-synced passwords.
>
> The following example adds a `KeychainItem</api/macos/keychainitem>` for an application and assigns a password.
>
> ``` xojo
> Var newItem As KeychainItem
> If System.KeychainCount > 0 Then
>   newItem = New KeychainItem
>   ' Indicate the name of the application
>   newItem.ServiceName = "MyApplication"
>
>   ' Create a new keychain item for the application and assign the password
>   System.Keychain.AddPassword(newItem, "SecretPassword")
> Else
>   System.Beep
>   MessageBox("You don't have a key chain.")
> End If
>
> Exception err As KeychainException
>   MessageBox("Can't add item: " + err.Message)
> ```

<div id="keychain.constructor0">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Keychain.Constructor

**Constructor**(Index As `Integer</api/data_types/integer>`)

> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> `Constructors</api/language/constructor>` are special methods called when you create an object with the `New</api/language/new>` keyword and pass in the parameters above.
>
> </div>
>
> Gives you a reference to any <span class="title-ref">Keychain</span> known by the <span class="title-ref">Keychain</span> manager. The *Index* value should be in the range from 0 to `System.KeychainCount<system.keychaincount>` - 1.
>
> This constructor is in a `For...Next</api/language/loops/for...next>` loop that instantiates a <span class="title-ref">Keychain</span> for each for each <span class="title-ref">Keychain</span> item. It populates a ListBox with the list of keychains.
>
> ``` xojo
> #If TargetMacOS
>   Declare Function KCGetKeychainName Lib "Carbon" (keychain As Integer, keychainName As Ptr) As Integer
>
>   Var i As Integer
>   Var err As Integer
>   Var kc As Keychain
>   Var kcName As MemoryBlock
>
>   kcName = New MemoryBlock(256)
>
>   For i = 0 To System.KeychainCount - 1
>     kc = New Keychain(i)
>
>     If kc = Nil Then
>       MessageBox("Keychain(" + i.ToString + ") returned nil")
>     Else
>       err = KCGetKeychainName(kc.Handle, kcName)
>
>       If err <> 0 Then
>         MessageBox("KCGetKeychainName returned " + err.ToString)
>       Else
>         ListBox1.AddRow(kcName.PString(0))
>       End If
>     End If
>   Next
> #EndIf
> ```

<div id="keychain.findpassword">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Keychain.FindPassword

**FindPassword**(`ByRef</api/language/byref>` KCItem As `KeychainItem</api/macos/keychainitem>`, `Optional</api/language/optional>` Synced As `Boolean</api/data_types/boolean>` = False) As `String</api/data_types/string>`

> Attempts to find the password for an Item in the given <span class="title-ref">Keychain</span> that matches *KCItem*. At the end of a successful call, *KCItem* will point to the found <span class="title-ref">Keychain</span> Item. If it fails, it generates a `KeychainException</api/exceptions/keychainexception>`.
>
> When *Synced* is `True</api/language/true>`, the search is performed against the iCloud <span class="title-ref">Keychain</span> instead of the local <span class="title-ref">Keychain</span>. Note that when working with iCloud-synced passwords, *KCItem* will not contain a valid `Handle<keychainitem.handle>` after a successful call. See the Notes section for additional requirements when working with iCloud-synced passwords.
>
> The following example retrieves the password and displays it in a message box.
>
> ``` xojo
> Var itemToFind As KeychainItem
> Var password As String
>
> itemToFind = New KeychainItem
> ' Indicate the name of the application whose keychain item you wish to find
> itemToFind.ServiceName = "MyApplication"
>
> ' get application's password from the system keychain
> password = System.Keychain.FindPassword(itemToFind)
> MessageBox("The password for this item is: " + password)
>
> Exception err As KeychainException
>   MessageBox("Can't find item: " + err.Message)
> ```

<div id="keychain.lock">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Keychain.Lock

**Lock**(LockAll As `Boolean</api/data_types/boolean>`)

> Locks the <span class="title-ref">Keychain</span>.
>
> If *LockAll* is `True</api/language/true>`, it will lock all the Keychains on the system. Note from Apple: There is usually no need for an application to ever call Lock. Unless your application is directly responding to a user's request for a <span class="title-ref">Keychain</span> to be locked, it is recommended that you leave the <span class="title-ref">Keychain</span> unlocked so that the user does not have to unlock it again in another application.
>
> If it fails, it generates a `KeychainException</api/exceptions/keychainexception>`.
>
> ``` xojo
> System.Keychain.Lock(True)
> ```

<div id="keychain.unlock">

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

</div>

<div class="rst-class">

forsearch

</div>

Keychain.Unlock

**Unlock**(Password As `String</api/data_types/string>`)

> Unlocks the <span class="title-ref">Keychain</span> if the *Password* is the empty string ("").
>
> The system displays the standard Unlock dialog, and the passed <span class="title-ref">Keychain</span> will appear as the selected item in that dialog's pop-up menu.
>
> <div class="note">
>
> <div class="title">
>
> Note
>
> </div>
>
> Because of the way Apple has implemented this, if you pass an incorrect password once to a particular <span class="title-ref">Keychain</span>, the system will require human interaction from then on that <span class="title-ref">Keychain</span> until the system is rebooted.
>
> </div>
>
> If it fails, it generates a `KeychainException</api/exceptions/keychainexception>`.
>
> ``` xojo
> System.Keychain.UnLock("")
> ```

## Notes

The <span class="title-ref">Keychain</span> is a system-wide facility on macOS to store account passwords for applications. By taking advantage of the built-in <span class="title-ref">Keychain</span> facility, your users won't have to type their password if their <span class="title-ref">Keychain</span> is unlocked. You should always ask the user before storing something in the <span class="title-ref">Keychain</span>.

An equivalent technology to the Mac OS <span class="title-ref">Keychain</span> doesn't currently exist on other platforms, so the <span class="title-ref">Keychain</span> class is supported only on macOS.

### iCloud Keychain

To work with iCloud-synced passwords, pass `True</api/language/true>` for the *Synced* parameter of `AddPassword<keychain.addpassword>` and `FindPassword<keychain.findpassword>`. Be aware that when using iCloud-synced passwords, the <span class="title-ref">Keychain</span> item returned by `FindPassword<keychain.findpassword>` will not contain a valid `Handle<keychainitem.handle>` due to the nature of OS-backed SecureItems.

Working with iCloud-synced passwords requires that your macOS app be signed with a Provisioning Profile that includes the `keychain-access-groups` entitlement. The entitlement value must match your Team ID (for example, `BW7PU32485.*`), which must also match the certificate used to sign the app. See `Accessing the Keychain</topics/macos/accessing_the_keychain>` for more details.

## Sample code

The following example adds a `KeychainItem</api/macos/keychainitem>` for an application and assigns a password.

``` xojo
Var newItem As KeychainItem
If System.KeychainCount > 0 Then
  newItem = New KeychainItem
  ' Indicate the name of the application
  newItem.ServiceName = "MyApplication"

  Try
    ' Create a new keychain item for the application and assign the password
    System.Keychain.AddPassword(newItem, "SecretPassword")
  Catch error As KeychainException
    MessageBox("Can't add item: " + error.Message)
  End Try
Else
  System.Beep
  MessageBox("You don't have a key chain.")
End If
```

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The following example retrieves the password and displays it in a message box.

``` xojo
Var itemToFind As KeychainItem
Var password As String

itemToFind = New KeychainItem
' Indicate the name of the application whose keychain item you wish to find
itemToFind.ServiceName = "MyApplication"

Try
  ' get application's password from the system keychain
  password = System.Keychain.FindPassword(itemToFind)
  MessageBox("The password for this item is: " + password)
Catch Exception error As KeychainException
  MessageBox("Can't find item: " + error.Message)
End Try
```

## Compatibility

|                       |         |
|-----------------------|---------|
| **Project Types**     | Desktop |
| **Operating Systems** | macOS   |

<div class="seealso">

`Object</api/data_types/additional_types/object>` parent class; `KeychainItem</api/macos/keychainitem>` class; `KeychainException</api/exceptions/keychainexception>` error; `System</api/os/system>` module.

</div>
