C#實(shí)現(xiàn)將聊天數(shù)據(jù)發(fā)送加密
實(shí)踐過程
效果
代碼
public partial class Form1 : Form { public Form1() { InitializeComponent(); } #region 定義全局對(duì)象及變量 private IPEndPoint Server;//服務(wù)器端 private IPEndPoint Client;//客戶端 private Socket mySocket;//套接字 private EndPoint ClientIP;//IP地址 byte[] buffer, data;//接收緩存 bool blFlag = true;//標(biāo)識(shí)是否第一次發(fā)送信息 bool ISPort = false;//判斷端口打開 int SendNum1, ReceiveNum1, DisNum1; //記錄窗體加載時(shí)的已發(fā)送\已接收\丟失的數(shù)據(jù)報(bào) int SendNum2, ReceiveNum2, DisNum2; //記錄當(dāng)前已發(fā)送\已接收\丟失的數(shù)據(jù)報(bào) int SendNum3, ReceiveNum3, DisNum3; //緩存已發(fā)送\已接收\丟失的數(shù)據(jù)報(bào) int port;//端口號(hào) #endregion //異步接收信息 private void StartLister(IAsyncResult IAResult) { int Num = mySocket.EndReceiveFrom(IAResult, ref ClientIP); string strInfo = Encoding.Unicode.GetString(buffer, 0, Num); rtbContent.AppendText("用戶" + ClientIP.ToString()); rtbContent.AppendText(":"); rtbContent.AppendText("\r\n"); rtbContent.AppendText(DecryptDES(strInfo, "mrsoftxk"));//對(duì)接收到的信息進(jìn)行解密 rtbContent.AppendText("\r\n"); mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ClientIP, new AsyncCallback(StartLister), null); } //初始化已發(fā)送、已接收和丟失的數(shù)據(jù)報(bào) private void Form1_Load(object sender, EventArgs e) { if (blFlag == true) { IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties(); UdpStatistics myUdpStat = null; myUdpStat = NetInfo.GetUdpIPv4Statistics(); SendNum1 = Int32.Parse(myUdpStat.DatagramsSent.ToString()); ReceiveNum1 = Int32.Parse(myUdpStat.DatagramsReceived.ToString()); DisNum1 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString()); } } //設(shè)置端口號(hào) private void button4_Click(object sender, EventArgs e) { try { port = Convert.ToInt32(textBox4.Text); CheckForIllegalCrossThreadCalls = false; buffer = new byte[1024]; data = new byte[1024]; Server = new IPEndPoint(IPAddress.Any, port); Client = new IPEndPoint(IPAddress.Broadcast, port); ClientIP = (EndPoint)Server; mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); mySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); mySocket.Bind(Server); mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ClientIP, new AsyncCallback(StartLister), null); ISPort = true;//打開指定端口號(hào) } catch { } } //發(fā)送信息 private void button2_Click(object sender, EventArgs e) { if (ISPort == true)//判斷是否有打開的端口號(hào) { IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties(); UdpStatistics myUdpStat = null; myUdpStat = NetInfo.GetUdpIPv4Statistics(); try { if (blFlag == false)//非第一次發(fā)送 { SendNum2 = Int32.Parse(myUdpStat.DatagramsSent.ToString()); ReceiveNum2 = Int32.Parse(myUdpStat.DatagramsReceived.ToString()); DisNum2 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString()); textBox1.Text = Convert.ToString(SendNum2 - SendNum3); textBox2.Text = Convert.ToString(ReceiveNum2 - ReceiveNum3); textBox3.Text = Convert.ToString(DisNum2 - DisNum3); } SendNum2 = Int32.Parse(myUdpStat.DatagramsSent.ToString()); ReceiveNum2 = Int32.Parse(myUdpStat.DatagramsReceived.ToString()); DisNum2 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString()); SendNum3 = SendNum2; //記錄本次的發(fā)送數(shù)據(jù)報(bào) ReceiveNum3 = ReceiveNum2;//記錄本次的接收數(shù)據(jù)報(bào) DisNum3 = DisNum2; //記錄本次的丟失數(shù)據(jù)報(bào) if (blFlag == true)//第一次發(fā)送 { textBox1.Text = Convert.ToString(SendNum2 - SendNum1); textBox2.Text = Convert.ToString(ReceiveNum2 - ReceiveNum1); textBox3.Text = Convert.ToString(DisNum2 - DisNum1); blFlag = false; } } catch (Exception ex) { MessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } string str = EncryptDES(rtbSend.Text, "mrsoftxk");//加密要發(fā)送的信息 data = Encoding.Unicode.GetBytes(str); mySocket.SendTo(data, data.Length, SocketFlags.None, Client); rtbSend.Text = ""; } else { MessageBox.Show("請(qǐng)首先打開端口!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); button4.Focus(); } } //清屏 private void button1_Click(object sender, EventArgs e) { rtbContent.Clear(); } //退出 private void button3_Click(object sender, EventArgs e) { Application.Exit(); } //按<Ctrl+Enter>組合鍵發(fā)送信息 private void rtbSend_KeyDown(object sender, KeyEventArgs e) { //當(dāng)同時(shí)按下Ctrl和Enter時(shí),發(fā)送消息 if (e.Control && e.KeyValue == 13) { e.Handled = true; button2_Click(this, null); } } //聊天記錄隨時(shí)滾動(dòng) private void rtbContent_TextChanged(object sender, EventArgs e) { rtbContent.ScrollToCaret(); } private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };//密鑰 #region DES加密字符串 ///<summary> ///DES加密字符串 ///</summary> ///<param name="str">待加密的字符串</param> ///<param name="key">加密密鑰,要求為8位</param> ///<returns>加密成功返回加密后的字符串,失敗返回源字符串</returns> public string EncryptDES(string str, string key) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8)); byte[] rgbIV = Keys; byte[] inputByteArray = Encoding.UTF8.GetBytes(str); DESCryptoServiceProvider myDES = new DESCryptoServiceProvider(); MemoryStream MStream = new MemoryStream(); CryptoStream CStream = new CryptoStream(MStream, myDES.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); CStream.Write(inputByteArray, 0, inputByteArray.Length); CStream.FlushFinalBlock(); return Convert.ToBase64String(MStream.ToArray()); } catch { return str; } } #endregion #region DES解密字符串 ///<summary> ///DES解密字符串 ///</summary> ///<param name="str">待解密的字符串</param> ///<param name="key">解密密鑰,要求為8位,和加密密鑰相同</param> ///<returns>解密成功返回解密后的字符串,失敗返源字符串</returns> public string DecryptDES(string str, string key) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(key); byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(str); DESCryptoServiceProvider myDES = new DESCryptoServiceProvider(); MemoryStream MStream = new MemoryStream(); CryptoStream CStream = new CryptoStream(MStream, myDES.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); CStream.Write(inputByteArray, 0, inputByteArray.Length); CStream.FlushFinalBlock(); return Encoding.UTF8.GetString(MStream.ToArray()); } catch { return str; } } #endregion }
partial class Form1 { /// <summary> /// 必需的設(shè)計(jì)器變量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的資源。 /// </summary> /// <param name="disposing">如果應(yīng)釋放托管資源,為 true;否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗體設(shè)計(jì)器生成的代碼 /// <summary> /// 設(shè)計(jì)器支持所需的方法 - 不要 /// 使用代碼編輯器修改此方法的內(nèi)容。 /// </summary> private void InitializeComponent() { this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.rtbContent = new System.Windows.Forms.RichTextBox(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.rtbSend = new System.Windows.Forms.RichTextBox(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.textBox4 = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.button4 = new System.Windows.Forms.Button(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.splitContainer1.Location = new System.Drawing.Point(4, 4); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.rtbContent); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); this.splitContainer1.Size = new System.Drawing.Size(430, 364); this.splitContainer1.SplitterDistance = 240; this.splitContainer1.SplitterWidth = 3; this.splitContainer1.TabIndex = 1; // // rtbContent // this.rtbContent.BackColor = System.Drawing.Color.White; this.rtbContent.BorderStyle = System.Windows.Forms.BorderStyle.None; this.rtbContent.Dock = System.Windows.Forms.DockStyle.Fill; this.rtbContent.Location = new System.Drawing.Point(0, 0); this.rtbContent.Name = "rtbContent"; this.rtbContent.ReadOnly = true; this.rtbContent.Size = new System.Drawing.Size(428, 238); this.rtbContent.TabIndex = 9; this.rtbContent.Text = ""; this.rtbContent.TextChanged += new System.EventHandler(this.rtbContent_TextChanged); // // splitContainer2 // this.splitContainer2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.rtbSend); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.button1); this.splitContainer2.Panel2.Controls.Add(this.button2); this.splitContainer2.Panel2.Controls.Add(this.button3); this.splitContainer2.Size = new System.Drawing.Size(430, 121); this.splitContainer2.SplitterDistance = 87; this.splitContainer2.SplitterWidth = 1; this.splitContainer2.TabIndex = 0; // // rtbSend // this.rtbSend.BorderStyle = System.Windows.Forms.BorderStyle.None; this.rtbSend.Dock = System.Windows.Forms.DockStyle.Fill; this.rtbSend.Location = new System.Drawing.Point(0, 0); this.rtbSend.Name = "rtbSend"; this.rtbSend.Size = new System.Drawing.Size(428, 85); this.rtbSend.TabIndex = 2; this.rtbSend.Text = ""; this.rtbSend.KeyDown += new System.Windows.Forms.KeyEventHandler(this.rtbSend_KeyDown); // // button1 // this.button1.Location = new System.Drawing.Point(294, 4); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(39, 23); this.button1.TabIndex = 4; this.button1.Text = "清屏"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(339, 4); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(38, 23); this.button2.TabIndex = 3; this.button2.Text = "發(fā)送"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Location = new System.Drawing.Point(383, 4); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(39, 23); this.button3.TabIndex = 5; this.button3.Text = "關(guān)閉"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.textBox3); this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.textBox2); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.textBox1); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Location = new System.Drawing.Point(440, 87); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(109, 165); this.groupBox1.TabIndex = 8; this.groupBox1.TabStop = false; this.groupBox1.Text = "數(shù)據(jù)傳輸信息"; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(20, 132); this.textBox3.Name = "textBox3"; this.textBox3.ReadOnly = true; this.textBox3.Size = new System.Drawing.Size(77, 21); this.textBox3.TabIndex = 7; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(8, 115); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(77, 12); this.label5.TabIndex = 6; this.label5.Text = "丟失數(shù)據(jù)報(bào):"; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(20, 86); this.textBox2.Name = "textBox2"; this.textBox2.ReadOnly = true; this.textBox2.Size = new System.Drawing.Size(77, 21); this.textBox2.TabIndex = 7; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(8, 69); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(89, 12); this.label4.TabIndex = 4; this.label4.Text = "已接收數(shù)據(jù)報(bào):"; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(20, 40); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(77, 21); this.textBox1.TabIndex = 6; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(8, 23); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(89, 12); this.label3.TabIndex = 2; this.label3.Text = "已發(fā)送數(shù)據(jù)報(bào):"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(8, 23); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(53, 12); this.label8.TabIndex = 2; this.label8.Text = "端口號(hào):"; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(20, 40); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(77, 21); this.textBox4.TabIndex = 0; this.textBox4.Text = "8888"; // // groupBox2 // this.groupBox2.Controls.Add(this.button4); this.groupBox2.Controls.Add(this.textBox4); this.groupBox2.Controls.Add(this.label8); this.groupBox2.Location = new System.Drawing.Point(440, 258); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(109, 110); this.groupBox2.TabIndex = 2; this.groupBox2.TabStop = false; this.groupBox2.Text = "端口設(shè)置"; // // button4 // this.button4.Location = new System.Drawing.Point(22, 68); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(75, 32); this.button4.TabIndex = 1; this.button4.Text = "設(shè)置"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(555, 372); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.splitContainer1); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "對(duì)數(shù)據(jù)報(bào)進(jìn)行加密保障通信完全"; this.Load += new System.EventHandler(this.Form1_Load); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.RichTextBox rtbContent; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.RichTextBox rtbSend; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button button4; }
到此這篇關(guān)于C#實(shí)現(xiàn)將聊天數(shù)據(jù)發(fā)送加密的文章就介紹到這了,更多相關(guān)C#聊天數(shù)據(jù)發(fā)送加密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)鼠標(biāo)移動(dòng)到曲線圖上顯示值的方法
這篇文章主要介紹了C#實(shí)現(xiàn)鼠標(biāo)移動(dòng)到曲線圖上顯示值的方法,是C#的WinForm窗體程序設(shè)計(jì)中非常實(shí)用的技巧,需要的朋友可以參考下2014-10-10C#使用smtp發(fā)送帶附件的郵件實(shí)現(xiàn)方法
這篇文章主要介紹了C#使用smtp發(fā)送帶附件的郵件實(shí)現(xiàn)方法,可直接將string類型結(jié)果保存為附件,實(shí)例中備有相應(yīng)的注釋便于理解,需要的朋友可以參考下2014-11-11C#實(shí)現(xiàn)自定義動(dòng)畫鼠標(biāo)的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)自定義動(dòng)畫鼠標(biāo)效果,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12C# paddlerocrsharp識(shí)別身份證號(hào)的實(shí)現(xiàn)示例
paddlerocrsharp可以進(jìn)行圖片識(shí)別,本文主要介紹了C# paddlerocrsharp識(shí)別身份證號(hào)的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02MessageBox的Buttons和三級(jí)聯(lián)動(dòng)效果
這篇文章主要介紹了MessageBox的Buttons和三級(jí)聯(lián)動(dòng)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11