UserGuide

Keychain Usage

From Xojo Documentation

You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!

The Keychain is a Mac feature used for storing account passwords for applications. By taking advantage of the keychain, your users do not have to type their password if their keychain is unlocked on their system.

Use the Keychain class to access Mac Keychains for your applications. The classes are: Keychain, KeychainItem and KeychainException.

You should always ask for permission from the user before storing anything in a keychain. You use the System module to get a reference to the default Keychain. You use the KeychainItem class to create, update or find items in the Keychain. If you have more than one Keychain, then you can use the KeyChain constructor to access specific key chains by number.

This code stores a password in the default Keychain:

Var newItem As KeychainItem
If System.KeychainCount > 0 Then
newItem = New KeychainItem
// Indicate the name of the application
newItem.ServiceName = "MyApplication"
// Assign a password to the item
System.Keychain.AddPassword(newItem, "SecretPassword")
Else
System.Beep
MessageBox("You don't have a key chain.")
End If

Exception e As KeychainException
MessageBox("Keychain error: " + e.Message)

And this code retrieves the password:

Var itemToFind As KeychainItem
Var password As String
itemToFind = New KeychainItem
// Name to find
ItemToFind.ServiceName = "MyApplication"
// Get the password
password = System.Keychain.FindPassword(itemToFind)
MessageBox("Password: " + password)

Exception e As KeychainException
MessageBox("Keychain error: " + e.Message)

See Also

Keychain, KeychainItem KeychainException classes