我有一个问题,我试图以 base64 格式发送数据。来自客户端的发送效果很好。但是,如果我试图在服务器上反编译 base64,我仍然总是出错,base64 字符无效。
我正在寻找一种方法,将数据从客户端加密到服务器并在服务器上解密,以实现安全传输。
我的代码显示 atm 是这样的: 客户:
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(ipAddress, ipAddressPort, new AsyncCallback(testA), null);
protected static void testA (IAsyncResult ar) {
socket.EndConnect(ar);
string str = EncodeTo64("Hello world!");
socket.BeginSend(System.Text.Encoding.UTF8.GetBytes(str), 0, str.Length, SocketFlags.None, new AsyncCallback(testB), socket);
}
protected static void testB (IAsyncResult ar) {
socket.EndSend(ar);
socket.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(testC), socket);
}
protected static void testC (IAsyncResult ar) {
socket.EndReceive(ar);
MessageBox.Show(System.Text.Encoding.UTF8.GetString(bytes));
}
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes
= System.Convert.FromBase64String(encodedData);
string returnValue =
System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
服务器:
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 4444);
serverSocket.Bind(ipEndPoint);
serverSocket.Listen(4);
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
protected static byte[] byteData = new byte[1024];
private void OnAccept(IAsyncResult ar)
{
Socket clientSocket = serverSocket.EndAccept(ar);
//Start listening for more clients
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
//Once the client connects then start receiving the commands from her
// Create the state object.
clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(OnReceive), clientSocket);
}
private void OnReceive(IAsyncResult ar) {
Socket clientSocket = (Socket)ar.AsyncState;
clientSocket.EndReceive(ar);
MessageBox.Show(DecodeFrom64(System.Text.Encoding.UTF8.GetString(byteData)));
}
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes
= System.Convert.FromBase64String(encodedData);
string returnValue =
System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
public void OnSend(IAsyncResult ar) {
Socket client = (Socket)ar.AsyncState;
client.EndSend(ar);
}