如何创建与MultiPeerConnectivity一起使用的SecIdentityRef?
问题描述:
我需要实现认证部分MultiPeer Connectivity交换Swift iOS应用程序。所以我需要在创建MCSession
时创建一个SecIdentityRef
对象(如MCSession(peer: myPeerId, securityIdentity: secIdentity, encryptionPreference: MCEncryptionPreference.Required)
)。如何创建与MultiPeerConnectivity一起使用的SecIdentityRef?
我已经创建了一个带钥匙串访问的X509证书并将其保存到.p12文件。我也有一个可以使用的.cgi和.der格式的证书。
我想知道这些证书是否值得在我的应用程序中使用,以及如何使用它?是否可以将证书直接放在项目目录中并将其数据导入到应用程序中,还是需要使用服务器来提供证书?
最后但并非最不重要,我不知道如何从给定的证书创建SecIdentityRef
。我试图浏览苹果开发者的类MCSession
,SecIdentityRef
,SecCertificateRef
甚至CFData
的参考,但我找不到任何可能帮助我的东西。
答
我想出了如何导入Multipeer Connectivity会话建立的证书。
在下面的例子中,我们假设我们在supportedFiles/certificate.p12下有证书。此外,由于我读过证书管理API不支持不受保护的证书,因此您的证书必须由密码保护。
func getIdentity (password : String?) -> SecIdentityRef? {
// Load certificate file
let path = NSBundle.mainBundle().pathForResource("certificate", ofType : "p12")
let p12KeyFileContent = NSData(contentsOfFile: path!)
if (p12KeyFileContent == nil) {
NSLog("Cannot read PKCS12 file from \(path)")
return nil
}
// Setting options for the identity "query"
let options = [String(kSecImportExportPassphrase):password ?? ""]
var citems: CFArray? = nil
let resultPKCS12Import = withUnsafeMutablePointer(&citems) { citemsPtr in
SecPKCS12Import(p12KeyFileContent!, options, citemsPtr)
}
if (resultPKCS12Import != errSecSuccess) {
return nil
}
// Recover the identity
let items = citems! as NSArray
let myIdentityAndTrust = items.objectAtIndex(0) as! NSDictionary
let identityKey = String(kSecImportItemIdentity)
let identity = myIdentityAndTrust[identityKey] as! SecIdentity
print("identity : ", identity)
return identity as SecIdentityRef
}
但是,我仍然不知道在应用程序文件中是否有证书是安全威胁。
编辑:感谢neilco,他的片断帮我建立我的解决方案。