我正在使用NSStream / CFStream套接字连接到我的服务器,现在想要使用SSL加密。 我有一个自签名的p12文件,但现在绝对想到我现在如何在我的流中使用它。 我在XCode中导入了p12文件,读取它,将其转换为NSData并使用此代码读取证书
let path = NSBundle.mainBundle().pathForResource("certificate", ofType: "p12")
let certData = NSData(contentsOfFile: path!)
let passDictionary:NSMutableDictionary = NSMutableDictionary()
passDictionary.setValue("passphrase", forKey: kSecImportExportPassphrase as String)
var items: CFArray?
let error = SecPKCS12Import(certData!, passDictionary, &items)
但我现在不知道该怎么办。
我尝试将它与我的溪流一起使用
inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey:NSStreamSocketSecurityLevelKey)
outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
inputStream!.setProperty(items, forKey: kCFStreamSSLCertificates as String)
outputStream!.setProperty(items, forKey: kCFStreamSSLCertificates as String)
但是在尝试连接时我得到了ErrorCode 9807。如何正确提取证书并告诉我的应用程序信任它们?
更新
我将上面的代码更改为:
let path = NSBundle.mainBundle().pathForResource("CERTNAME", ofType: "p12")
let certData = NSData(contentsOfFile: path!)
let passDictionary:NSMutableDictionary = NSMutableDictionary()
passDictionary.setValue("meetsapp", forKey: kSecImportExportPassphrase as String)
var items: CFArray?
let error = SecPKCS12Import(certData!, passDictionary, &items)
let unwrappedItems = items! as [AnyObject]
let certDict = unwrappedItems[0] as! [String:AnyObject]
var certs = [certDict["identity"]!]
for c in certDict["chain"]! as! [AnyObject]
{
certs.append(c as! SecCertificateRef)
}
items = certs
如果我打印“项目”,它看起来像这样:
[<SecIdentityRef: 0x7faa834d9930>, <cert(0x7faa834d4860) s: CERTNAME i: CA-NAME>, <cert(0x7faa8585ea00) s: CA-NAME i: CA-NAME>]
如果我没有错,那么属性kCFStreamSSLCertificates的必需格式,但我仍然得到相同的错误代码。我假设我的应用程序有信任问题,但我该如何解决它们?