首页 > 解决方案 > 如何将自定义字符串添加到 NWProtocolTLS.Options()

问题描述

Multipeer Connectivity 框架有一个参数可以添加 peerID,例如设备名称:

var peerID: MCPeerID!
var mcSession: MCSession!

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

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

我查看了 Apple 在其TicTacToe 示例应用程序中的做法。他们使用安全密码,但我不需要任何复杂的东西,我只希望设备名称或 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
}

标签: iosswiftnetworking

解决方案


推荐阅读