我正在将一些旧的 Objective-C 代码转换为 Swift,这样我就可以摆脱一些不推荐使用的方法,但我一直在崩溃,到目前为止,我似乎无法弄清楚是什么原因造成的。我从 P12 证书中获取了一个私钥,这种方法似乎可以正常工作,直到我到达我实际需要从 CFArray 获取字典的部分,即使数组中有值,应用程序也会不断崩溃. 这是我拥有的代码:
func privateKeyFromCertificate(p12Name: String, withPassword password: String) -> SecKeyRef {
let resourcePath: String = NSBundle.mainBundle().pathForResource(p12Name, ofType: "p12")!
let p12Data: NSData = NSData(contentsOfFile: resourcePath)!
let key : NSString = kSecImportExportPassphrase as NSString
let options : NSDictionary = [key : password]
var privateKeyRef: SecKeyRef? = nil
var items : CFArray?
let securityError: OSStatus = SecPKCS12Import(p12Data, options, &items)
let description : CFString = CFCopyDescription(items)
print(description)
if securityError == noErr && CFArrayGetCount(items) > 0 {
let objects : CFDictionaryRef = CFArrayGetValueAtIndex(items, 0) as! CFDictionaryRef
let kString : NSString = kSecImportItemIdentity as NSString
let identity : SecIdentityRef = CFDictionaryGetValue(objects, unsafeAddressOf(kString)) as! SecIdentityRef
let securityError = SecIdentityCopyPrivateKey(identity, &privateKeyRef)
if securityError != noErr {
privateKeyRef = nil
}
}
return privateKeyRef!
}
该应用程序在我尝试从 CFArray 获取 CFDictiionaryRef 的第一行的 if 语句中不断崩溃。我添加了一行来打印 CFArray 的描述作为测试,它确实有值:
<CFArray 0x7fd2d2e8c2f0 [0x10b61f7b0]>{type = mutable-small, count = 1, values = (
0 : <CFBasicHash 0x7fd2d2e8c190 [0x10b61f7b0]>{type = mutable dict, count = 3,entries =>
0 : <CFString 0x10bfdd2c0 [0x10b61f7b0]>{contents = "trust"} = <SecTrustRef: 0x7fd2d2e8ad30>
1 : <CFString 0x10bfdd300 [0x10b61f7b0]>{contents = "identity"} = <SecIdentityRef: 0x7fd2d2e80390>
2 : <CFString 0x10bfdd2e0 [0x10b61f7b0]>{contents = "chain"} = <CFArray 0x7fd2d2d016e0 [0x10b61f7b0]>{type = mutable-small, count = 1, values = (
0 : <cert(0x7fd2d2e8c610) s: Client (IPHONE-WebService) i:Client (IPHONE-WebService)>)}}