Skip to content

Instantly share code, notes, and snippets.

@thomsmed
Created December 30, 2021 10:29
Show Gist options
  • Select an option

  • Save thomsmed/f5d8077c3320fe0a6fadeeabdaa594a5 to your computer and use it in GitHub Desktop.

Select an option

Save thomsmed/f5d8077c3320fe0a6fadeeabdaa594a5 to your computer and use it in GitHub Desktop.
Print all available keychain items (iOS, iPadOS, macOS, watchOS, tvOS)
//
// printKeychainItems.swift
//
import Security
enum SecClass: String, CaseIterable {
// Available keychain item classes:
// https://developer.apple.com/documentation/security/keychain_services/keychain_items/item_class_keys_and_values#1678477
case genericPassword
case internetPassword
case certificate
case key
case identity
var cfString: CFString {
switch self {
case .genericPassword:
return kSecClassGenericPassword
case .internetPassword:
return kSecClassInternetPassword
case .certificate:
return kSecClassCertificate
case .key:
return kSecClassKey
case .identity:
return kSecClassIdentity
}
}
}
func printKeychainItems() {
SecClass.allCases.forEach { secClass in
let searchQuery = [
kSecClass: secClass.cfString,
kSecMatchLimit: kSecMatchLimitAll,
kSecReturnAttributes: true,
] as CFDictionary
var result: CFTypeRef?
let status = SecItemCopyMatching(searchQuery, &result)
switch status {
case errSecItemNotFound:
print("No items of class \(secClass.rawValue) in keychain")
case errSecSuccess:
let items = result as? [[CFString : Any]] ?? []
print("\(items.count) items of class \(secClass.rawValue):")
items.forEach { item in
print("Access group:", item[kSecAttrAccessGroup] ?? "")
print("Service:", item[kSecAttrService] ?? "")
print("Account:", item[kSecAttrAccount] ?? "")
print("Description:", item[kSecAttrDescription] ?? "")
print("Available attributes:", item.keys)
}
default:
print("Something went wrong")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment