UserGuide

Keychain Usage

From Xojo Documentation

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:

Dim 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
Beep
MsgBox("You don't have a key chain.")
End If

Exception e As KeyChainException
MsgBox("Keychain error: " + e.Message)

And this code retrieves the password:

Dim itemToFind As KeyChainItem
Dim password As String
itemToFind = New KeyChainItem
// Name to find
ItemToFind.ServiceName = "MyApplication"
// Get the password
password = System.KeyChain.FindPassword(itemToFind)
MsgBox("Password: " + password)

Exception e As KeyChainException
MsgBox("Keychain error: " + e.Message)