使用SSL确保通信中的数据安全

8/10/2015来源:ASP.NET技巧人气:1229

使用SSL确保通信中的数据安全

aaa

bbb

        #region Server        /// <summary>        /// 用于保存非对称加密(数字证书)的公钥        /// </summary>        PRivate string publicKey = string.Empty;        /// <summary>        /// 用于保存非对称加密(数字证书)的私钥        /// </summary>        private string pfxKey = string.Empty;        ///===========================        ///服务端代码        ///===========================        /// <summary>        /// 用于跟客户端通信的Socket        /// </summary>        private Socket serverCommunicateSocket;        /// <summary>        /// 定义接收缓存块的大小        /// </summary>        private static int serverBufferSize = 1024;        /// <summary>        /// 缓存块        /// </summary>        byte[] bytesReceivedFromClient = new byte[serverBufferSize];        /// <summary>        /// 密钥K        /// </summary>        private string key = string.Empty;        StringBuilder messageFromClient = new StringBuilder();        /// <summary>        /// 开启服务器        /// </summary>        private void btnStartServer_Click(object sender, EventArgs e)        {            //先生成数字证书(模拟,及非对称密钥对)            RSAKeyInit();            //负责侦听            StartListen();        }        void RSAKeyInit()        {            RSAProcessor.CreateRSAKey(ref publicKey, ref pfxKey);            //本例中,先指定一对公钥、私钥            publicKey = "<RSAKeyValue><Modulus>httkQLJ52ODWcIoDont7izs0Kn8OIr3IJ+Q5DC3RgzojjphvHN/5N4miVN+U0fz405o53CRP0PUghyq0rbHZNj7ZW1M1Vh/ne4lDvP/q44QerhYewTUwT92tHj8GyYxvegkp98vT95YkjFJRByQCXrhKBW64ziqnDL2n9LeUPBM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";            pfxKey = "<RSAKeyValue><Modulus>httkQLJ52ODWcIoDont7izs0Kn8OIr3IJ+Q5DC3RgzojjphvHN/5N4miVN+U0fz405o53CRP0PUghyq0rbHZNj7ZW1M1Vh/ne4lDvP/q44QerhYewTUwT92tHj8GyYxvegkp98vT95YkjFJRByQCXrhKBW64ziqnDL2n9LeUPBM=</Modulus><Exponent>AQAB</Exponent><P>vZPGLPJBxtjhoSSt7OXvAqalRU8IXmPbojk7/j9f1DW1DRCLwof6MjJqt4uAY9D/L/GPJh9zIddeVM3lkr9s6Q==</P><Q>tht1LlLi7XQJHsVfgJ1ewBjjOOzQSfmO+RTClWXKquuup4pblF51jSDK+5VlyibD5chzeO1mxjvzkEfcJNgTmw==</Q><DP>kZXfdfrhKqy5sX+ylaAKydViTHSiL6KuM8mSWfEfTZ+lF5BiVBUKvevb6nKWOZFxt8bhMNysFQwI5EVujSC2QQ==</DP><DQ>hEsqM77vMEWNopcMLCkm/jKWT3JqVnM/lF+qhFHwi36v4PK4WO7OQvpBu8bqrZK/2ZxnlsAQW46OAJDTsshuZQ==</DQ><InverseQ>BfZy74k5EqN6l7faYHSYvqWuRMSWwp4dCXF43uT8wcf3kciYxIkbaNNY56ulJbCAN2SyDQkD3PF+Sp3qtJZ/Vg==</InverseQ><D>ADbI6fFekCGLNZKCfveDMq1dX9PjydpTPvz1ujc4ZeTpuYg0ZO9WDeiCAXB5Y/vqySstfFPybHp3Gr/OmZf2qEbKQlK6Ztms3R30rnqk/2/XHtAm5AeVLhf03q/+76mtvgtUTspgth55JpIKGYNKcQTJBbgepbyVT26YjMwrMoE=</D></RSAKeyValue>";        }        void StartListen()        {            ipEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.103"), 8009);            //负责侦听的socket            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            listenSocket.Bind(iep);            listenSocket.Listen(50);            listenSocket.BeginAccept(new AsyncCallback(this.Accepted), listenSocket);            ListBoxShow("开始侦听...");            btnStartServer.Enabled = false;        }        /// <summary>        /// 负责客户端的连接,并开始将自己置于接收状态        /// </summary>        void Accepted(IAsyncResult result)        {            Socket listenSocket = result.AsyncState as Socket;            //初始化和客户端进行通信的socket            serverCommunicateSocket = listenSocket.EndAccept(result);            ListBoxShow("有客户端连接到...");            serverCommunicateSocket.BeginReceive(bytesReceivedFromClient, 0, serverBufferSize, SocketFlags.None,                new AsyncCallback(this.ReceivedFromClient), null);        }        /// <summary>        /// 负责处理接收自客户端的数据        /// </summary>        void ReceivedFromClient(IAsyncResult result)        {            int read = serverCommunicateSocket.EndReceive(result);            if (read > 0)            {                messageFromClient.Append(UTF32Encoding.Default.GetString(bytesReceivedFromClient, 0, read));                //处理并显示数据                ProcessAndShowInServer();                serverCommunicateSocket.BeginReceive(bytesReceivedFromClient, 0, serverBufferSize, 0,                    new AsyncCallback(ReceivedFromClient), null);            }        }        private void ProcessAndShowInServer()        {            string msg = messageFromClient.ToString();            //如果接收到<EOF>表示完成一次,否则继续将自己置于接收状态            if (msg.IndexOf("<EOF>") > -1)            {                //如果客户端发送Key,则负责初始化Key                if (msg.IndexOf("<KEY>") > -1)                {                    //用私钥解密发送过来的Key信息                    key = RSAProcessor.RSADecrypt(pfxKey, msg.Substring(0, msg.Length - 10));                    ListBoxShow(string.Format("接收到客户端密钥:{0}", key));                }                else                {                    //解密SSL通道中发送过来的密文并显示                    ListBoxShow(string.Format("接收到客户端消息:{0}", RijndaelProcessor.DecryptString(msg.Substring(0, msg.Length - 5), key)));                }            }            messageFromClient.Clear();        }        /// <summary>        /// 负责向客户端发送数据        /// </summary>        private void btnStartSendToClient_Click(object sender, EventArgs e)        {            //加密消息体            string msg = string.Format("{0}{1}", RijndaelProcessor.EncryptString(DateTime.Now.ToString(), key), "<EOF>");            RijndaelProcessor.DecryptString(msg.Substring(0, msg.Length - 5), key);            byte[] msgBytes = UTF32Encoding.Default.GetBytes(msg);            serverCommunicateSocket.BeginSend(msgBytes, 0, msgBytes.Length, SocketFlags.None, null, null);            ListBoxShow(string.Format("发送:{0}", msg));        }        /// <summary>        /// 界面显示        /// </summary>        private void ListBoxShow(string argMsg)        {            listBoxServer.BeginInvoke(new Action(() =>            {                listBoxServer.Items.Add(argMsg);            }));        }        #endregion
        #region Client        /// <summary>        /// 用于保存非对称加密(数字证书)的公钥        /// </summary>        private string publicKey = "<RSAKeyValue><Modulus>httkQLJ52ODWcIoDont7izs0Kn8OIr3IJ+Q5DC3RgzojjphvHN/5N4miVN+U0fz405o53CRP0PUghyq0rbHZNj7ZW1M1Vh/ne4lDvP/q44QerhYewTUwT92tHj8GyYxvegkp98vT95YkjFJRByQCXrhKBW64ziqnDL2n9LeUPBM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";        ///==============================        /// 客户端代码        ///==============================        ///用于跟踪服务器通信的socket        private Socket clientCommunicateSocket;        /// <summary>        /// 用于暂存接收到的字符串        /// &l