关于NetWork 框架连接TLS

引言

此代码是写完公司项目后整理的并没有测试,仅仅提供思路

读取p12证书请添加到Data扩展

 func identity(password: String) throws -> SecIdentity {
        var importResult: CFArray? = nil
        let err = SecPKCS12Import(
            self 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
    }

定义连接context

var conn: NWConnection!

在扩展里面加入代码连接TLS

func connectedToHost(ip:String,port:UInt16,queue:String,localCert:String?,pass:String?) -> Bool {
        let queue = DispatchQueue(label:queue)
        let host = NWEndpoint.Host(ip)
        let port = NWEndpoint.Port(integerLiteral: port)
        //Create TLS Configureation
        let options = NWProtocolTLS.Options()
        //Set Local Cert
        if localCert != nil && pass != nil {
            
            let data = try? Data(contentsOf: URL(string: localCert!)!)
            let certArray:SecIdentity? = try?data?.identity(password: "12345678")
            
            if certArray != nil{
                sec_protocol_options_set_local_identity(options.securityProtocolOptions,sec_identity_create(certArray!)!)
            }else{
                delegate?.didDisConnect(err: "Load Local Cert Fail")
            }
            
        }
        //Set Very Cert 
        //always trust
            sec_protocol_options_set_verify_block(options.securityProtocolOptions, {
                (sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in
                sec_protocol_verify_complete(true)
                
            }, queue)
        //create Connection
        conn = NWConnection(host: host, port: port, using: NWParameters(tls: options))
        //start
        conn.start(queue: queue)
   
        return true
    }

数据读写

//send data
func send(data:Data,tag:Int16){
        conn.send(content: data, completion: .contentProcessed({ (error) in
            if let error = error {
                //Data Send Error
                print(error)
                self.conn.cancel()
            } else {
                //Data send Success
                print("send Success")
            }
            guard delegate != nil else{return}
            delegate?.didWriteData(err: error, tag: tag)
        }))
    }
//rev data
     func receive(length:Int,tag:Int16){
        conn.receive(minimumIncompleteLength: length, maximumLength: length) { (data, context, isComplete, error) in
            if let error = error {
                print(error)
                //具体实现需要判断错误再断开
                self.conn.cancel()
                return
            }
            if let data = data {
                print("receive:\(data)")
            }

            if isComplete {
                self.conn.cancel()
            }
        }
    }
    //close connect
    func cannel(){
        conn.cancel()
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值