枚举我的iOS应用程序中的所有Keychain项目

时间:2012-06-10 07:11:22

标签: ios security keychain

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

它可能与SecItemCopyMatching()有关,但该函数的文档不是很清楚(我在网上找不到合适的样本)。

6 个答案:

答案 0 :(得分:52)

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

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

由于SecItemCopyMatching至少需要返回SecItem的类,我们创建一个包含所有类的数组...

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

...对于每个类,在查询中设置类,调用SecItemCopyMatching,并记录结果。

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(至少找到一个项目)

答案 1 :(得分:5)

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

open func getAllKeyChainItemsOfClass(_ secClass: String) -> [String:String] {

        let 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! {
                if let key = item[kSecAttrAccount] as? String, 
                   let value = item[kSecValueData] as? Data {
                   values[key] = String(data: value, encoding:.utf8) 
                }
            }
        }

        return values
    }

答案 2 :(得分:4)

迅速将4更新为@Cosmin答案

open func getAllKeyChainItemsOfClass(_ secClass: String) -> [String:String] {

            let query: [String: Any] = [
                kSecClass as String : secClass,
                kSecReturnData as String  : kCFBooleanTrue,
                kSecReturnAttributes as String : kCFBooleanTrue,
                kSecReturnRef as String : kCFBooleanTrue,
                kSecMatchLimit as String: 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! {
                    if let key = item[kSecAttrAccount as String] as? String,
                        let value = item[kSecValueData as String] as? Data {
                        values[key] = String(data: value, encoding:.utf8)
                    }
                }
            }

            return values
        }

答案 3 :(得分:3)

带有xcode 9.1的Swift 3版本

func getAllKeyChainItemsOfClass(_ secClass: String) -> [String:String] {

    let query: [String: Any] = [
        kSecClass as String : secClass,
        kSecReturnData as String  : kCFBooleanTrue,
        kSecReturnAttributes as String : kCFBooleanTrue,
        kSecReturnRef as String : kCFBooleanTrue,
        kSecMatchLimit as String : 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! {
            if let key = item[kSecAttrAccount as String] as? String,
                let value = item[kSecValueData as String] as? Data {
                values[key] = String(data: value, encoding:.utf8)
            }
        }
    }

    return values
}

可以像:

一样调用
debugPrint(getAllKeyChainItemsOfClass(kSecClassGenericPassword as String))

答案 4 :(得分:1)

其他Swift代码片段似乎都有些混乱。您实际上不必在MutablePointers周围花很多时间,并且您可能想要进行适当的错误管理。我通过调整Apple documentation中的代码在Swift中实现了我的版本。这适用于使用Xcode 11的用户。

let query: [String: Any] = [kSecClass as String: kSecClassInternetPassword, // change the kSecClass for your needs
                            kSecMatchLimit as String: kSecMatchLimitAll,
                            kSecReturnAttributes as String: true,
                            kSecReturnRef as String: true]
var items_ref: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &items_ref)
guard status != errSecItemNotFound else { throw KeychainError.noPassword }
guard status == errSecSuccess else { throw KeychainError.unhandledError(status: status) }
let items = items_ref as! Array<Dictionary<String, Any>>

// Now loop over the items and do something with each item
for item in items {
    // Sample code: prints the account name
    print(item[kSecAttrAccount as String] as? String)
}

答案 5 :(得分:0)

已更新为在字典中包含kSecClassIdentity和kSecClassCertificate信息

我也不认为有必要调用 withUnsafeMutablePointer(to:_:)

func getAllKeyChainItemsOfClass(_ secClass: String) -> [String:AnyObject] {

    let query: [String: Any] = [
        kSecClass as String : secClass,
        kSecReturnData as String  : true,
        kSecReturnAttributes as String : true,
        kSecReturnRef as String : true,
        kSecMatchLimit as String: kSecMatchLimitAll
    ]

    var result: AnyObject?

    let lastResultCode = withUnsafeMutablePointer(to: &result) {
        SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
    }

//  this also works, although I am not sure if it is as save as calling withUnsafeMutabePointer
//  let lastResultCode = SecItemCopyMatching(query as CFDictionary, &result)

    var values = [String: AnyObject]()
    if lastResultCode == noErr {
        let array = result as? Array<Dictionary<String, Any>>

        for item in array! {
            if let key = item[kSecAttrAccount as String] as? String,
                let value = item[kSecValueData as String] as? Data {
                values[key] = String(data: value, encoding:.utf8) as AnyObject?
            }
            // including identities and certificates in dictionary
            else if let key = item[kSecAttrLabel as String] as? String,
                let value = item[kSecValueRef as String] {
                values[key] = value as AnyObject
            }
        }
    }

    return values
}