枚举我的iOS应用程序中的所有钥匙串项目

什么是最简单的方式(从我的应用程序)获取存储在钥匙串中的所有项目?

它可能与SecItemCopyMatching()有关,但该函数的文档不是很清楚(我没有find一个体面的样本在网上)。

SecItemCopyMatching是正确的要求。 首先我们build立我们的查询字典,以便在字典中返回项目的属性,并返回所有项目:

 NSMutableDictionary *query = [NSMutableDictionary dictionaryWithObjectsAndKeys: (__bridge id)kCFBooleanTrue, (__bridge id)kSecReturnAttributes, (__bridge id)kSecMatchLimitAll, (__bridge id)kSecMatchLimit, nil]; 

由于SecItemCopyMatching至less需要返回SecItem的类,所以我们创build一个包含所有类的数组…

 NSArray *secItemClasses = [NSArray arrayWithObjects: (__bridge id)kSecClassGenericPassword, (__bridge id)kSecClassInternetPassword, (__bridge id)kSecClassCertificate, (__bridge id)kSecClassKey, (__bridge id)kSecClassIdentity, nil]; 

…并为每个类,在我们的查询中设置类,调用SecItemCopyMatching ,并logging结果。

 for (id secItemClass in secItemClasses) { [query setObject:secItemClass forKey:(__bridge id)kSecClass]; CFTypeRef result = NULL; SecItemCopyMatching((__bridge CFDictionaryRef)query, &result); NSLog(@"%@", (__bridge id)result); if (result != NULL) CFRelease(result); } 

在生产代码中,应该检查OSStatus返回的SecItemCopyMatchingerrSecItemNotFound (找不到项目)还是errSecSuccess (至lessfind一个项目)。

Swift 3+版本,也返回键(kSecAttrAccount):

 open func getAllKeyChainItemsOfClass(_ secClass: String) -> [String:String] { var query: [String: Any] = [ kSecClass : secClass, kSecReturnData : kCFBooleanTrue, kSecReturnAttributes : kCFBooleanTrue, kSecReturnRef : kCFBooleanTrue, kSecMatchLimit : kSecMatchLimitAll ] var result: AnyObject? let lastResultCode = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } var values = [String:String]() if lastResultCode == noErr { let array = result as? Array<Dictionary<String, Any>> for item in array! { let key : String = item[kSecAttrAccount] as! String let value : Data = item[kSecValueData] as! Data values[key] = String(data: value, encoding:.utf8) } } return values }