ios - 如何将自定义字符串添加到 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
}
解决方案
推荐阅读
- bash - ssh-add <(echo "$SSH_PRIVATE_KEY") 在 gitlab-ci 上出现错误
- go - 预缓存 Golang 模板或更有效的方法来做到这一点
- c# - Python os.walk 返回的文件少于 C# Directory.GetFiles
- matlab - 如何隐藏 imshow 图像并将最终图像保存到文件夹
- db2 - DBeaver 不会在数据库导航器中正确显示某些模式
- python - 信号处理 - 为什么在我的截止频率处没有完全滤除信号?
- javascript - 我的 HTML div 标签不包含列表,也不显示底部边框
- gradle - 如何在 gradle 构建期间从 xcore 模型生成代码
- excel - CopyFromRecordSet 具有无效的转换异常
- css - 某些 SASS 设置似乎不起作用