简体   繁体   English

如何在发送到服务器时加密我的消息?

[英]How can I encrypt my message when sending to the server?

I would like to encrypt my message when sending to the server from client, how can I do it? 我想从客户端发送到服务器时加密我的消息,我该怎么办?

Client 客户

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;

namespace SocketClient
{
    public partial class SocketClient : Form
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream = default(NetworkStream);
        string readData = null;

        public SocketClient()
        {
            InitializeComponent();
        }

        private void getMessage()
        {
            while (true)
            {
                serverStream = clientSocket.GetStream();
                int buffSize = 0;
                byte[] inStream = new byte[10025];
                buffSize = clientSocket.ReceiveBufferSize;
                serverStream.Read(inStream, 0, buffSize);
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                readData = "" + returndata;
                msg();
            }
        }

        private void msg()
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(msg));
            else
                textDisplay.Text = textDisplay.Text + Environment.NewLine + " >> " + readData;
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            readData = "Connected to NYP Chat Server ...";
            msg();
            //clientSocket.Connect("127.0.0.1", 8888);
            clientSocket.Connect(textIP.Text, Convert.ToInt32(textPort.Text));
            serverStream = clientSocket.GetStream();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textName.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            Thread ctThread = new Thread(getMessage);
            ctThread.Start();
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            // Show msg box if no server is connected
            if (serverStream == null)
            {
                MessageBox.Show("Please connect to a server first!");
                return;
            }

            // Send text
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            // Clear text
            textSend.Text = "";
        }

        private void textDisplay_TextChanged(object sender, EventArgs e)
        {
            textDisplay.SelectionStart = textDisplay.Text.Length;
            textDisplay.ScrollToCaret();
            textDisplay.Refresh();
        }

        private void textSend_TextChanged(object sender, EventArgs e)
        {
            buttonSend.Enabled = !string.IsNullOrEmpty(textSend.Text);
        }
    }
}

server 服务器

using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        public static Hashtable clientsList = new Hashtable();

        static void Main(string[] args)
        {
            //TcpListener serverSocket = new TcpListener(portFromAppConfig);

            TcpListener serverSocket = new TcpListener(9999);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;

            serverSocket.Start();
            Console.WriteLine("Welcome to NYP Chat Server ");
            counter = 0;
            while ((true))
            {
                counter += 1;
                clientSocket = serverSocket.AcceptTcpClient();

                byte[] bytesFrom = new byte[10025];
                string dataFromClient = null;

                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

                clientsList.Add(dataFromClient, clientSocket);

                broadcast(dataFromClient + " Connected ", dataFromClient, false);

                Console.WriteLine(dataFromClient + " has join the chat room ");
                handleClient client = new handleClient();
                client.startClient(clientSocket, dataFromClient, clientsList);
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine("exit");
            Console.ReadLine();
        }

        public static void broadcast(string msg, string uName, bool flag)
        {
            foreach (DictionaryEntry Item in clientsList)
            {
                TcpClient broadcastSocket;
                broadcastSocket = (TcpClient)Item.Value;
                NetworkStream broadcastStream = broadcastSocket.GetStream();
                Byte[] broadcastBytes = null;

                if (flag == true)
                {
                    broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
                }
                else
                {
                    broadcastBytes = Encoding.ASCII.GetBytes(msg);
                }

                broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
                broadcastStream.Flush();
            }
        }  //end broadcast function
    }//end Main class


    public class handleClient
    {
        TcpClient clientSocket;
        string clNo;
        Hashtable clientsList;

        public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
        {
            this.clientSocket = inClientSocket;
            this.clNo = clineNo;
            this.clientsList = cList;
            Thread ctThread = new Thread(doChat);
            ctThread.Start();
        }

        private void doChat()
        {
            int requestCount = 0;
            byte[] bytesFrom = new byte[10025];
            string dataFromClient = null;
            Byte[] sendBytes = null;
            string serverResponse = null;
            string rCount = null;
            requestCount = 0;

            while ((true))
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
                    rCount = Convert.ToString(requestCount);

                    Program.broadcast(dataFromClient, clNo, true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }//end while
        }//end doChat
    } //end class handleClient
}//end namespace

Absolute simplest way is to rip all the code you wrote and just use WCF. 绝对最简单的方法是翻录您编写的所有代码并使用WCF。

Next simplest way is to use a secure stream instead of the raw Network Stream, like SslStream or NegotiateStream . 下一个最简单的方法是使用安全流而不是原始网络流,如SslStreamNegotiateStream There a full blown sample at Secure Streams Sample that shows both the client and the server for NTLM/Kerberos and SChannel protocols (aka SSL/TLS). Secure Streams Sample上有一个完整的示例,它显示了NTLM / Kerberos和SChannel协议(也称为SSL / TLS)的客户端和服务器。

One thing you should absolutely not do is write your own encryption. 你绝对应该做的一件事是编写自己的加密。 Encrypting messages is trivial and you'll find a myriad samples on the web. 加密消息是微不足道的,你会在网上找到无数的样本。 But creating a key exchange protocol so you actually have something to encrypt with is one of the hardest tasks in crypto. 但是创建一个密钥交换协议,所以你实际上有一些东西需要加密,这是加密中最难的任务之一。 Use one of the industry acknowledged key exchange schemes like Kerberos or SSL/TLS, and these are already implemented in the two stream classes I linked. 使用业界公认的密钥交换方案之一,如Kerberos或SSL / TLS,这些已经在我链接的两个流类中实现。

C# provides a namespace for cryptography System.Security.Cryptography... for start you could check that out... Or try to implement a cryptography algorithm like Vernamm which is the simplest and easiest to implement. C#为加密System.Security.Cryptography提供了一个命名空间...为了开始你可以检查出来......或者尝试实现像Vernamm这样最简单,最容易实现的加密算法。 Or if you want to be fully secured you should use both the System.Security.Cryptography namespace the System.Security.Cryptography.X509Certificates namespace. 或者,如果您想要完全安全,则应使用System.Security.Cryptography命名空间System.Security.Cryptography.X509Certificates命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM