A lightweight Swift library for convenient keychain access.
HPKeychain supports iOS 15, tvOS 15, macOS 12, watchOS 9, and visionOS 1.
HPKeychain is available through the Swift Package Manager.
Add the package to the dependencies of your Package.swift file:
dependencies: [
.package(url: "https://github.com/henrik-dmg/hpkeychain", from: "1.0.0")
]Then add the product to the target that uses it:
.target(
name: "MyTarget",
dependencies: [
.product(name: "HPKeychain", package: "hpkeychain")
]
)- Open your project in Xcode.
- Choose File > Add Package Dependencies….
- Enter the URL
https://github.com/henrik-dmg/hpkeychain. - Click Add Package.
- Select the target that uses HPKeychain.
HPKeychain separates two concerns. A credential describes what the keychain item contains. A query describes how to find the item in the keychain.
UsernamePasswordCredentialholds a username and a password (asData).GenericPasswordQueryfinds an item with a service identifier.InternetPasswordQueryfinds an item with a server.
Keychain is the entry point. Each method takes a query. The methods that write an item also take a credential.
To store a new item, call save(_:for:) with a credential and a query.
let query = InternetPasswordQuery(server: "https://github.com")
let credential = UsernamePasswordCredential(username: "admin", password: Data("secret".utf8))
try Keychain.save(credential, for: query)To read items, call credentials(for:) with a query. The method returns an array of credentials for the type of the query. The array is empty when no item matches.
let query = GenericPasswordQuery(serviceIdentifier: "com.example.myapp")
let credentials = try Keychain.credentials(for: query)
if let credential = credentials.first {
print(credential.username)
}To change an existing item, call update(_:for:) with the new credential and the query that finds the item. The method throws an error when no item matches.
let query = InternetPasswordQuery(server: "https://github.com")
let updatedCredential = UsernamePasswordCredential(username: "admin", password: Data("someMoreSecurePassword".utf8))
try Keychain.update(updatedCredential, for: query)To delete items, call deleteAll(matching:) with a query. The method deletes all items that match. It does not throw an error when no item matches.
let query = InternetPasswordQuery(server: "https://github.com")
try Keychain.deleteAll(matching: query)To support a new type of keychain item, add a type that conforms to Credential and a type that conforms to CredentialQuery. You do not change Keychain.