代码之家  ›  专栏  ›  技术社区  ›  sha

通过API检索签名标识列表

  •  0
  • sha  · 技术社区  · 6 年前

    这与MacOS有关。

    我需要从本机Mac应用程序内部检索使用API导入并在keychain上可用的签名身份(证书+私钥)列表。我可以运行以下命令行并分析结果:

    > /usr/bin/security find-identity -v -p codesigning
    > 
    >  1) 0123456789ABCDEF0123456789ABCDEF01234567 "iPhone Developer: John Doe (GTHESFW12)"
    >  2) 0123456789ABCDEF0123456789ABCDEF01234567 "iPhone Distribution: ABC Inc (12356DGEWS)"
    > 2 valid identities found
    

    但我正在寻找一种通过本机安全API实现这一点的方法。有办法吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   sha    6 年前

    @Jamesbucanek,比你的链接!下面是使用keychain services api生成的代码。可能对其他人有用:

    let query: [String: Any] = [
        kSecClass as String: kSecClassIdentity,
        kSecReturnRef as String: kCFBooleanTrue,
        kSecMatchLimit as String: kSecMatchLimitAll
    ]
    var items: CFTypeRef?
    
    // Get list of all SecIdentity from Keychain without limiting search and without any filtering applied
    guard SecItemCopyMatching(query as CFDictionary, &items) == errSecSuccess, let array = items as? NSArray else {
        return
    }
    
    for item in array {
        let identity = item as! SecIdentity
        var certificate: SecCertificate?
    
        // Get SecCertificate out of SecIdentity object (it contains both SecCertificate and SecKey
        if SecIdentityCopyCertificate(identity, &certificate) == errSecSuccess {
    
            var commonName: CFString?
            // Print name for each certificate
            if SecCertificateCopyCommonName(certificate!, &commonName) == errSecSuccess {
                print(commonName! as String)
            }
        }
    }