- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
这个程序是关于建立一个服务器和多个客户端之间的连接。握手的过程是客户端生成一个散列值并发送给服务器。服务器端生成一对公钥和私钥并对散列值进行加密,并将加密后的散列值与公钥一起发送回客户端。
我的问题是服务器没有响应我想要的数据,服务器只会响应公钥的签名(加密哈希)。
我的声誉不够高,无法发布结果图片,所以我会直接打出来
另一个问题是我不知道如何修复服务器挂起程序,在 StartListening() 方法的服务器异步类中存在无限循环
有 2 个不同的项目,一个用于服务器,一个用于客户端
服务端代码
异步服务器套接字代码
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Security.Cryptography;
// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder ();
}
public class AsynchronousServerSocket : MonoBehaviour
{
// Thread signal.
public static ManualResetEvent allDone =
new ManualResetEvent (false);
public AsynchronousServerSocket ()
{
}
public Socket listener;
public Server ServerClass;
public ASCIIEncoding myAscii =
new ASCIIEncoding ();
public void StartListening ()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry ("127.0.0.1");
IPAddress ipAddress = ipHostInfo.AddressList [0];
IPEndPoint localEndPoint = new IPEndPoint (ipAddress, 11000);
// Create a TCP/IP socket.
listener = new Socket
(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try {
listener.Bind (localEndPoint);
listener.Listen (1024);
while (true) {
// Set the event to nonsignaled state.
allDone.Reset ();
// Start an asynchronous socket to listen for connections.
Debug.Log ("Waiting for a connection...");
listener.BeginAccept
(new AsyncCallback (AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne ();
}
//StartCoroutine("StupidUnityHang");
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
public IEnumerator StupidUnityHang ()
{
do {
// Set the event to nonsignaled state.
allDone.Reset ();
// Start an asynchronous socket to listen for connections.
Debug.Log ("Waiting for a connection...");
listener.BeginAccept
(new AsyncCallback (AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne ();
yield return new WaitForSeconds (1);
} while(true);
}
public void AcceptCallback (IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set ();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept (ar);
// Create the state object.
StateObject state = new StateObject ();
state.workSocket = handler;
handler.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback (StageOne), state);
allDone.WaitOne ();
handler.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback (StageTwo), state);
//allDone.Set();
}
// sending client the signature and the public key
public void StageOne (IAsyncResult ar)
{
String content = String.Empty;
String check = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive (ar);
if (bytesRead > 0) {
state.sb.Append (Encoding.ASCII.GetString (state.buffer, 0, bytesRead));
content = state.sb.ToString ();
byte[] hashByte = myAscii.GetBytes (content);
ServerClass.GeneratePublicPrivateKey ();
byte [] signature = ServerClass.SendEncryptHash (hashByte);
content = myAscii.GetString (signature);
Send (handler, content);
}
}
public void StageTwo (IAsyncResult ar)
{
String content = String.Empty;
String check = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive (ar);
if (bytesRead > 0) {
//state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
//content = state.sb.ToString();
//if(content =="PK")
//{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
RSAParameters publicKey = ServerClass.SendPublicKey ();
rsaCSP.ImportParameters (publicKey);
content = rsaCSP.ToXmlString (false);
Send (handler, content);
//}
}
}
private void Send (Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes (data);
// Begin sending the data to the remote device.
handler.BeginSend (byteData, 0, byteData.Length, 0,
new AsyncCallback (SendCallback), handler);
}
private void SendCallback (IAsyncResult ar)
{
try {
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend (ar);
Debug.Log ("Sent {0} bytes to client." + bytesSent);
handler.Shutdown (SocketShutdown.Both);
handler.Close ();
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
}
服务器进程代码
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System;
public class Server : MonoBehaviour
{
public RSAParameters rsaPrivateKey;
public RSAParameters rsaPublicKey;
public void GeneratePublicPrivateKey ()
{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
rsaPrivateKey = rsaCSP.ExportParameters (true);
rsaPublicKey = rsaCSP.ExportParameters (false);
}
public RSAParameters SendPublicKey ()
{
return rsaPublicKey;
}
public byte[] HashAndSign (byte[] encrypted)
{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
SHA1Managed hash = new SHA1Managed ();
byte[] hashedData;
rsaCSP.ImportParameters (rsaPrivateKey);
hashedData = hash.ComputeHash (encrypted);
return rsaCSP.SignHash (hashedData, CryptoConfig.MapNameToOID ("SHA1"));
}
public byte[] SendEncryptHash (byte[] tmp)
{
return HashAndSign (tmp);
}
public byte[] SendEncryptAESHash (byte[]hash, byte[]key, byte[]IV)
{
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
rsaCSP.ImportParameters (rsaPrivateKey);
byte[] decryptedSessionKey = rsaCSP.Decrypt (key, false);
byte[] decryptedSessionIV = rsaCSP.Decrypt (IV, false);
return encrypt_function (hash, decryptedSessionKey, decryptedSessionIV);
}
private static byte[] encrypt_function (byte[] PlainBytes, byte[] Key, byte[] IV)
{
RijndaelManaged Crypto = null;
MemoryStream MemStream = null;
ICryptoTransform Encryptor = null;
CryptoStream Crypto_Stream = null;
try {
Crypto = new RijndaelManaged ();
Crypto.Key = Key;
Crypto.IV = IV;
MemStream = new MemoryStream ();
Encryptor = Crypto.CreateEncryptor (Crypto.Key, Crypto.IV);
Crypto_Stream = new CryptoStream (MemStream, Encryptor, CryptoStreamMode.Write);
Crypto_Stream.Write (PlainBytes, 0, PlainBytes.Length);
} finally {
if (Crypto != null)
Crypto.Clear ();
Crypto_Stream.Close ();
}
return MemStream.ToArray ();
}
}
服务器主程序
using UnityEngine;
using System.Collections;
public class ServerProgram : MonoBehaviour
{
public AsynchronousServerSocket AsynchronousServerClass;
public void Start ()
{
AsynchronousServerClass.StartListening ();
}
}
客户端代码
异步客户端类
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Security.Cryptography;
// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder ();
}
public class AsynchronousClientSocket : MonoBehaviour
{
// The port number for the remote device.
private const int port = 11000;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent (false);
private static ManualResetEvent sendDone = new ManualResetEvent (false);
private static ManualResetEvent receiveDone = new ManualResetEvent (false);
// The response from the remote device.
private String response = String.Empty;
public Client ClientClass;
public ASCIIEncoding myAscii = new ASCIIEncoding ();
public void StartClient ()
{
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry ("127.0.0.1");
IPAddress ipAddress = ipHostInfo.AddressList [0];
IPEndPoint remoteEP = new IPEndPoint (ipAddress, port);
// Create a TCP/IP socket.
Socket client = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect (remoteEP, new AsyncCallback (ConnectCallback), client);
connectDone.WaitOne ();
byte[] hashByte = ClientClass.SendHash ();
string hashString = myAscii.GetString (hashByte);
// Send test data to the remote device.
Send (client, hashString);
sendDone.WaitOne ();
// Receive the response from the remote device.
Receive (client);
receiveDone.WaitOne ();
// Write the response to the console.
Debug.Log ("Signature: " + response);
byte[] signature = myAscii.GetBytes (response);
Send (client, "PK");
sendDone.WaitOne ();
Receive (client);
receiveDone.WaitOne ();
Debug.Log ("PublicKey: " + response);
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider ();
rsaCSP.FromXmlString (response);
RSAParameters publicKey = rsaCSP.ExportParameters (false);
if (ClientClass.VerifyHash (publicKey, hashByte, signature)) {
Debug.Log ("success");
} else {
Debug.Log ("problem");
}
// Release the socket.
client.Shutdown (SocketShutdown.Both);
client.Close ();
} catch (Exception e) {
Console.WriteLine (e.ToString ());
}
}
private void ConnectCallback (IAsyncResult ar)
{
try {
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect (ar);
Debug.Log ("Socket connected to {0}" + client.RemoteEndPoint.ToString ());
// Signal that the connection has been made.
connectDone.Set ();
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
private void Receive (Socket client)
{
try {
// Create the state object.
StateObject state = new StateObject ();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback (ReceiveCallback), state);
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
private void ReceiveCallback (IAsyncResult ar)
{
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive (ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so far.
state.sb.Append (Encoding.ASCII.GetString (state.buffer, 0, bytesRead));
// Get the rest of the data.
client.BeginReceive (state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback (ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString ();
}
// Signal that all bytes have been received.
receiveDone.Set ();
}
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
private void Send (Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes (data);
// Begin sending the data to the remote device.
client.BeginSend (byteData, 0, byteData.Length, 0, new AsyncCallback (SendCallback), client);
}
private void SendCallback (IAsyncResult ar)
{
try {
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend (ar);
Debug.Log ("Sent {0} bytes to server." + bytesSent);
// Signal that all bytes have been sent.
sendDone.Set ();
} catch (Exception e) {
Debug.Log (e.ToString ());
}
}
}
客户端处理类方法
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System;
public class Client : MonoBehaviour
{
public string hash;
public byte[] sessionKeyByte;
public byte[] sessionIVByte;
public byte[] sessionKey;
public byte[] sessionIV;
static readonly char[] AvailableCharacters = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '`', '~', '-',
'@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '=', '+', '/',
'{', '}', '[', ']', '|','\\', ':', ';', '"','\'', '<', '>', ',',
'.', '?', '!'
};
internal static string GenerateIdentifier (int length)
{
char[] identifier = new char[length];
byte[] randomData = new byte[length];
RNGCryptoServiceProvider rng =
new RNGCryptoServiceProvider ();
rng.GetBytes (randomData);
for (int idx = 0; idx < identifier.Length; idx++) {
int pos =
randomData [idx] % AvailableCharacters.Length;
identifier [idx] = AvailableCharacters [pos];
}
return new string (identifier);
}
public byte[] SendHash ()
{
hash = GenerateIdentifier (8);
ASCIIEncoding myAscii = new ASCIIEncoding ();
return myAscii.GetBytes (hash);
}
public bool VerifyHash
(RSAParameters rsaParams, byte[] signedData, byte[] signature)
{
RSACryptoServiceProvider rsaCSP =
new RSACryptoServiceProvider ();
SHA1Managed hash = new SHA1Managed ();
byte[] hashedData;
rsaCSP.ImportParameters (rsaParams);
hashedData = hash.ComputeHash (signedData);
return rsaCSP.VerifyHash
(hashedData, CryptoConfig.MapNameToOID ("SHA1"), signature);
}
public void EncryptSessionKey (RSAParameters temp)
{
RijndaelManaged Crypto = new RijndaelManaged ();
RSACryptoServiceProvider rsaCSP =
new RSACryptoServiceProvider ();
rsaCSP.ImportParameters (temp);
sessionKey = Crypto.Key;
sessionIV = Crypto.IV;
sessionKeyByte = rsaCSP.Encrypt (sessionKey, false);
sessionIVByte = rsaCSP.Encrypt (sessionIV, false);
}
public byte[] SendSessionKey ()
{
return sessionKeyByte;
}
public byte[] SendSessionIV ()
{
return sessionIVByte;
}
private static string decrypt_function (
byte[] Cipher_Text, byte[] Key, byte[] IV)
{
RijndaelManaged Crypto = null;
MemoryStream MemStream = null;
ICryptoTransform Decryptor = null;
CryptoStream Crypto_Stream = null;
StreamReader Stream_Read = null;
string Plain_Text;
try {
Crypto = new RijndaelManaged ();
Crypto.Key = Key;
Crypto.IV = IV;
MemStream = new MemoryStream
(Cipher_Text);
Decryptor = Crypto.CreateDecryptor
(Crypto.Key, Crypto.IV);
Crypto_Stream = new CryptoStream
(MemStream, Decryptor, CryptoStreamMode.Read);
Stream_Read = new StreamReader
(Crypto_Stream);
Plain_Text = Stream_Read.ReadToEnd ();
} finally {
if (Crypto != null)
Crypto.Clear ();
MemStream.Flush ();
MemStream.Close ();
}
return Plain_Text;
}
public string DecryptHash (byte[] temp)
{
return decrypt_function (temp, sessionKey, sessionIV);
}
public bool VerifySessionKey (string temp)
{
if (temp == hash) {
return true;
} else {
return false;
}
}
public void ClearHash ()
{
hash = "";
}
}
客户端主程序
using UnityEngine;
using System.Collections.Generic;
public class ClientProgram : MonoBehaviour
{
public string log;
public AsynchronousClientSocket AsynchronousClientClass;
public void OnGUI ()
{
GUILayout.BeginArea (new Rect (Screen.width / 2 - 250, Screen.height / 2 - 250, 500, 500));
GUI.TextArea (new Rect (0, 0, 500, 300), log);
if (GUI.Button (new Rect (200, 310, 100, 30), "Connect")) {
AsynchronousClientClass.StartClient ();
}
GUILayout.EndArea ();
}
}
需要帮助来格式化我的代码,我尝试了很多次来格式化我的代码,但它一直弹出“你的帖子似乎包含代码......甚至都已经在代码选项卡中了。我将所有代码左对齐,然后它运行良好...
我是统一方面的新手,也是网络和安全编程方面的新手,我希望有人能指出我更好的写作方式。
解决了
最佳答案
哎哟……我头疼……试试更简单的东西,比如……
http://ccoder.co.uk/files/sockets.zip
这应该让你继续:)
这是我拥有的一个更大项目(用于统一游戏的 MMO 服务器系统)的代码子集。我真的应该找个时间完成它!!!
关于c# - 需要帮助解决有关异步服务器套接字的一些逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24384090/
我正在尝试用 C 语言编写一个使用 gstreamer 的 GTK+ 应用程序。 GTK+ 需要 gtk_main() 来执行。 gstreamer 需要 g_main_loop_run() 来执行。
我已经使用 apt-get 安装了 opencv。我得到了以下版本的opencv2,它工作正常: rover@rover_pi:/usr/lib/arm-linux-gnueabihf $ pytho
我有一个看起来像这样的 View 层次结构(基于其他答案和 Apple 的使用 UIScrollView 的高级 AutoLayout 指南): ScrollView 所需的2 个步骤是: 为 Scr
我尝试安装 udev。 udev 在 ./configure 期间给我一个错误 --exists: command not found configure: error: pkg-config and
我正在使用 SQLite 3。我有一个表,forums,有 150 行,还有一个表,posts,有大约 440 万行。每个帖子都属于一个论坛。 我想从每个论坛中选择最新帖子的时间戳。如果我使用 SEL
使用 go 和以下包: github.com/julienschmidt/httprouter github.com/shwoodard/jsonapi gopkg.in/mgo.v2/bson
The database仅包含 2 个表: 钱包(100 万行) 事务(1500 万行) CockroachDB 19.2.6 在 3 台 Ubuntu 机器上运行 每个 2vCPU 每个 8GB R
我很难理解为什么在下面的代码中直接调用 std::swap() 会导致编译错误,而使用 std::iter_swap 编译却没有任何错误. 来自 iter_swap() versus swap() -
我有一个非常简单的 SELECT *用 WHERE NOT EXISTS 查询条款。 SELECT * FROM "BMAN_TP3"."TT_SPLDR_55E63A28_59358" SELECT
我试图按部分组织我的 .css 文件,我需要从任何文件访问文件组中的任何类。在 Less 中,我可以毫无问题地创建一个包含所有文件导入的主文件,并且每个文件都导入主文件,但在 Sass 中,我收到一个
Microsoft.AspNet.SignalR.Redis 和 StackExchange.Redis.Extensions.Core 在同一个项目中使用。前者需要StackExchange.Red
这个问题在这里已经有了答案: Updating from Rails 4.0 to 4.1 gives sass-rails railties version conflicts (4 个答案) 关
我们有一些使用 Azure DevOps 发布管道部署到的现场服务器。我们已经使用这些发布管道几个月了,没有出现任何问题。今天,我们在下载该项目的工件时开始出现身份验证错误。 部署组中的节点显示在线,
Tip: instead of creating indexes here, run queries in your code – if you're missing any indexes, you
你能解释一下 Elm 下一个声明中的意思吗? (=>) = (,) 我在 Elm architecture tutorial 的例子中找到了它 最佳答案 这是中缀符号。实际上,这定义了一个函数 (=>
我需要一个 .NET 程序集查看器,它可以显示低级详细信息,例如元数据表内容等。 最佳答案 ildasm 是 IL 反汇编程序,具有低级托管元数据 token 信息。安装 Visual Studio
我有两个列表要在 Excel 中进行比较。这是一个很长的列表,我需要一个 excel 函数或 vba 代码来执行此操作。我已经没有想法了,因此转向你: **Old List** A
Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。 想要改善这个问题吗?更新问题,以便将其作为on-topi
我正在学习 xml 和 xml 处理。我无法很好地理解命名空间的存在。 我了解到命名空间帮助我们在 xml 中分离相同命名的元素。我们不能通过具有相同名称的属性来区分元素吗?为什么命名空间很重要或需要
我搜索了 Azure 文档、各种社区论坛和 google,但没有找到关于需要在公司防火墙上打开哪些端口以允许 Azure 所有组件(blob、sql、compute、bus、publish)的简洁声明
我是一名优秀的程序员,十分优秀!