需要解析和比较证书值,但是其中一些作为Data返回,而不解析为字符串。大多数属性以数字或字符串形式返回,但是kSecPropertyKeyValueCFData的数组。需要像钥匙串访问一样显示类似的证书信息。

import Foundation
import Security

let query: [CFString: Any] = [
    kSecClass: kSecClassCertificate,
    kSecReturnAttributes: kCFBooleanTrue,
    kSecReturnRef: kCFBooleanTrue,
    kSecReturnData: kCFBooleanTrue,
    kSecMatchLimit: kSecMatchLimitAll
]

var result: AnyObject?
SecItemCopyMatching(query as CFDictionary, &result)
let certs: [SecCertificate] = (result as? [[CFString: Any]])?.map({ $0[kSecValueRef] as! SecCertificate }) ?? []

for cert in certs {
    if let values: [CFString:Any] = (SecCertificateCopyValues(cert, [kSecOIDExtendedKeyUsage] as CFArray, nil) as? [CFString:Any])?[kSecOIDExtendedKeyUsage] as? [CFString:Any] {

        // Expect to find `kSecOIDExtendedUseCodeSigning` value or something else
        // meaningful. How do I do that?

        print(
            "type:", values[kSecPropertyKeyType]!,
            "||| data values:", values[kSecPropertyKeyValue] as! [Data],
            "||| cString:", (values[kSecPropertyKeyValue] as! [CFData]).map({ String(cString: CFDataGetBytePtr($0)) }),
            "||| string:", (values[kSecPropertyKeyValue] as! [Data]).map({ String(data: $0, encoding: .utf8) })
        )
    }
}


粘贴在操场上,打印:

type: array ||| data values: [8 bytes] ||| cString: ["+\u{06}\u{01}\u{05}\u{05}\u{07}\u{03}\u{04}"] ||| string: [Optional("+\u{06}\u{01}\u{05}\u{05}\u{07}\u{03}\u{04}")]
type: array ||| data values: [9 bytes] ||| cString: ["*�H��cd\u{04}\t"] ||| string: [nil]


有些看上去像Unicode转义符,有些看上去像无效的字符串。任何帮助表示赞赏。

最佳答案

显然,OID值没有可读的字符串表示形式,而是常量,可以在google/der-ascii中找到。

例如,上述+\u{06}\u{01}\u{05}\u{05}\u{07}\u{03}\u{04}的输出与0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x04匹配,即email protection+0x2b字节)。

关于swift - 如何从SecCertificate中提取或比较kSecPropertyKeyValue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49489591/

10-12 07:36