Introduction
Welcome to the documentation for KeychainAccess – an open-source library for iOS apps that allows you to easily work with the iOS Keychain.
Installation
To install KeychainAccess, you can use one of the following methods:
- Using CocoaPods:
- Using Carthage, add the following line to your Cartfile:
- Manually:
- Download the latest release zip file.
- Extract the zip file and locate the
KeychainAccess.swift
file. - Drag and drop the
KeychainAccess.swift
file into your Xcode project.
pod 'KeychainAccess'
github "kishikawakatsumi/KeychainAccess"
Usage
To use KeychainAccess in your iOS app:
- Add
import KeychainAccess
to the file you want to use it in. - Create an instance of
Keychain
: - Saving a password:
- Fetching a password:
- Deleting a password:
let keychain = Keychain(service: "com.example.yourapp")
do { try keychain.set("your_password", key: "your_key") } catch { print("Error saving password: \\(error)") }
do { let password = try keychain.get("your_key") print("Fetched password: \\(password ?? "")") } catch { print("Error fetching password: \\(error)") }
do { try keychain.remove("your_key") } catch { print("Error deleting password: \\(error)") }
Keychain Configuration
When creating an instance of Keychain
, you can customize its behaviour using the available options:
- service: The service name that will be associated with the keychain. The default is the app’s bundle identifier.
- accessGroup: The access group to share keychain items with other apps. Default is
nil
. - alwaysSecure: A boolean indicating whether the item should be stored in the keychain only when the device is unlocked. The default is
false
. - accessibility: The accessibility level to use for the keychain item. Default is
.whenUnlocked
. - authenticationPolicy: The authentication policy to apply for accessing the keychain item. Default is
.userPresence
. - synchronizable: A boolean indicating whether the items should be synced with other devices through iCloud Keychain. Default is
false
. - useAccessControl: A boolean indicating whether the access control mechanism should be enabled for the keychain item. Default is
true
.
Security Recommendations
When working with the iOS Keychain, it is important to consider the following security recommendations:
- Always store sensitive data, such as passwords or encryption keys, in the Keychain instead of UserDefaults or other storage methods.
- When using
KeychainAccess
, make sure to choose appropriate accessibility levels and enable the access control mechanism. - Implement additional security measures, such as biometric authentication, to protect sensitive data stored in the keychain.
- Regularly review and update your app’s security practices to stay up-to-date with best practices and security guidelines.
Conclusion
Congratulations! You now have a basic understanding of KeychainAccess and how to use it in your iOS app. Explore the official GitHub repository for more advanced features and examples.