Using SSL from Swift

297 Views Asked by At

I'm trying to connect to IRC via SSL using CocoaAsyncSocket and I seem to be going wrong somewhere. Here's the code I'm working with:

func identity(named name: String, password: String) throws -> SecIdentity {
        let url = Bundle.main.url(forResource: name, withExtension: "p12")!
        let data = try Data(contentsOf: url)
        var importResult: CFArray? = nil
        let err = SecPKCS12Import(
            data as NSData,
            [kSecImportExportPassphrase as String: password] as NSDictionary,
            &importResult
        )
        guard err == errSecSuccess else {
            throw NSError(domain: NSOSStatusErrorDomain, code: Int(err), userInfo: nil)
        }
        let identityDictionaries = importResult as! [[String:Any]]
        return identityDictionaries[0][kSecImportItemIdentity as String] as! SecIdentity
}

public func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        let sslSettings = NSMutableDictionary()

        sslSettings[kCFStreamSSLCertificates] = try! identity(named: "ssl", password: "")
        sslSettings.addEntries(from: [kCFStreamSSLLevel: StreamSocketSecurityLevel.negotiatedSSL, kCFStreamSSLPeerName: host, kCFStreamSSLValidatesCertificateChain: false])
        socket?.startTLS(sslSettings as! [String : NSObject])
}

I'm just getting a "Socket closed by remote peer" error. Could there be an issue with the cert I've generated? Can't seem to find any information anywhere about how to generate a proper cert.

0

There are 0 best solutions below