代码之家  ›  专栏  ›  技术社区  ›  Lance Samaria

如何将自定义字符串添加到NWProtocolTLS.Options()

  •  0
  • Lance Samaria  · 技术社区  · 4 年前

    Multipeer Connectivity framework有一个参数来添加peerID,例如设备名:

    var peerID: MCPeerID!
    var mcSession: MCSession!
    
    peerID = MCPeerID(displayName: UIDevice.current.name)
    mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
    

    如何向NWProtocolTLS.Options()添加相同的内容?

    TicTacToe example app . 他们使用安全密码,但我不需要任何复杂的东西,我只需要设备名或uid来配合它。

    使用

    let tcpOptions = NWProtocolTCP.Options()
    tcpOptions.enableKeepalive = true
    tcpOptions.keepaliveIdle = 2
    
    let tls = tlsOptions(passcode: UIDevice.current.name)
    
    let params = NWParameters(tls: tls, tcp: tcpOptions)
        
    let connection = NWConnection(to: endpoint, using: params)
    

    苹果公司代码:

    // Create TLS options using a passcode to derive a pre-shared key.
    func tlsOptions(passcode: String) -> NWProtocolTLS.Options {
        let tlsOptions = NWProtocolTLS.Options()
    
        let authenticationKey = SymmetricKey(data: passcode.data(using: .utf8)!)
        var authenticationCode = HMAC<SHA256>.authenticationCode(for: "TicTacToe".data(using: .utf8)!, using: authenticationKey)
    
        let authenticationDispatchData = withUnsafeBytes(of: &authenticationCode) { (ptr: UnsafeRawBufferPointer) in
            DispatchData(bytes: ptr)
        }
    
        sec_protocol_options_add_pre_shared_key(tlsOptions.securityProtocolOptions,
                                                authenticationDispatchData as __DispatchData,
                                                stringToDispatchData("TicTacToe")! as __DispatchData)
        sec_protocol_options_append_tls_ciphersuite(tlsOptions.securityProtocolOptions,
                                                    tls_ciphersuite_t(rawValue: TLS_PSK_WITH_AES_128_GCM_SHA256)!)
        return tlsOptions
    }
    
    // Create a utility function to encode strings as pre-shared key data.
    func stringToDispatchData(_ string: String) -> DispatchData? {
        guard let stringData = string.data(using: .unicode) else {
            return nil
        }
        let dispatchData = withUnsafeBytes(of: stringData) { (ptr: UnsafeRawBufferPointer) in
            DispatchData(bytes: UnsafeRawBufferPointer(start: ptr.baseAddress, count: stringData.count))
        }
        return dispatchData
    }
    
    0 回复  |  直到 4 年前