2016-06-09 24 views
1

我需要實現認證部分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的參考,但我找不到任何可能幫助我的東西。

回答

0

我想出瞭如何導入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,他的片斷幫我建立我的解決方案。

相關問題