C#实现将聊天数据发送加密

作者:芝麻粒儿 时间:2022-09-10 05:56:35 

实践过程

效果

C#实现将聊天数据发送加密

代码

public partial class Form1 : Form
{
   public Form1()
   {
       InitializeComponent();
   }

#region 定义全局对象及变量
   private IPEndPoint Server;//服务器端
   private IPEndPoint Client;//客户端
   private Socket mySocket;//套接字
   private EndPoint ClientIP;//IP地址
   byte[] buffer, data;//接收缓存
   bool blFlag = true;//标识是否第一次发送信息
   bool ISPort = false;//判断端口打开
   int SendNum1, ReceiveNum1, DisNum1; //记录窗体加载时的已发送\已接收\丢失的数据报
   int SendNum2, ReceiveNum2, DisNum2; //记录当前已发送\已接收\丢失的数据报
   int SendNum3, ReceiveNum3, DisNum3; //缓存已发送\已接收\丢失的数据报
   int port;//端口号
   #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"));//对接收到的信息进行解密
       rtbContent.AppendText("\r\n");
       mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ClientIP, new AsyncCallback(StartLister), null);
   }

//初始化已发送、已接收和丢失的数据报
   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());
       }
   }

//设置端口号
   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;//打开指定端口号
       }
       catch { }
   }

//发送信息
   private void button2_Click(object sender, EventArgs e)
   {
       if (ISPort == true)//判断是否有打开的端口号
       {
           IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties();
           UdpStatistics myUdpStat = null;
           myUdpStat = NetInfo.GetUdpIPv4Statistics();
           try
           {
               if (blFlag == false)//非第一次发送
               {
                   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; //记录本次的发送数据报
               ReceiveNum3 = ReceiveNum2;//记录本次的接收数据报
               DisNum3 = DisNum2; //记录本次的丢失数据报
               if (blFlag == true)//第一次发送
               {
                   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");//加密要发送的信息
           data = Encoding.Unicode.GetBytes(str);
           mySocket.SendTo(data, data.Length, SocketFlags.None, Client);
           rtbSend.Text = "";
       }
       else
       {
           MessageBox.Show("请首先打开端口!", "提示", 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>组合键发送信息
   private void rtbSend_KeyDown(object sender, KeyEventArgs e)
   {
       //当同时按下Ctrl和Enter时,发送消息
       if (e.Control && e.KeyValue == 13)
       {
           e.Handled = true;
           button2_Click(this, null);
       }
   }

//聊天记录随时滚动
   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>
   /// 必需的设计器变量。
   /// </summary>
   private System.ComponentModel.IContainer components = null;

/// <summary>
   /// 清理所有正在使用的资源。
   /// </summary>
   /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
   protected override void Dispose(bool disposing)
   {
       if (disposing && (components != null))
       {
           components.Dispose();
       }
       base.Dispose(disposing);
   }

#region Windows 窗体设计器生成的代码

/// <summary>
   /// 设计器支持所需的方法 - 不要
   /// 使用代码编辑器修改此方法的内容。
   /// </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 = "发送";
       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 = "关闭";
       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 = "数据传输信息";
       //
       // 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 = "丢失数据报:";
       //
       // 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 = "已接收数据报:";
       //
       // 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 = "已发送数据报:";
       //
       // 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 = "端口号:";
       //
       // 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 = "端口设置";
       //
       // 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 = "设置";
       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 = "对数据报进行加密保障通信完全";
       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;
}

来源:https://blog.csdn.net/qq_27489007/article/details/128402676

标签:C#,数据,加密
0
投稿

猜你喜欢

  • 浅谈virtual、abstract方法和静态方法、静态变量理解

    2022-08-29 02:29:14
  • Spring5中的WebClient使用方法详解

    2023-08-05 14:50:24
  • Java ThreadLocal类使用详解

    2022-08-04 05:29:34
  • winform壁纸工具为图片添加当前月的日历信息

    2022-03-05 07:23:01
  • Filter、Servlet、Listener的学习_动力节点Java学院整理

    2021-08-12 00:05:49
  • MyBatis利用MyCat实现多租户的简单思路分享

    2022-08-16 18:58:33
  • java生成随机数的方法

    2023-12-12 12:49:51
  • java信号量控制线程打印顺序的示例分享

    2023-05-09 12:27:38
  • Java基础之详解HashSet的使用方法

    2023-08-04 20:18:59
  • java异常处理执行顺序详解try catch finally

    2022-10-01 04:10:10
  • SpringBoot整合TomCat实现本地图片服务器代码解析

    2021-07-30 16:34:19
  • 浅谈一下Spring中的createBean

    2023-06-08 22:01:26
  • FasfDFS整合Java实现文件上传下载功能实例详解

    2022-05-27 02:30:46
  • Spring Boot 实现图片上传并回显功能

    2021-10-11 17:45:20
  • Java JDK动态代理实现原理实例解析

    2022-04-23 05:19:10
  • Java生成word文档的示例详解

    2022-02-11 19:37:47
  • C#的内存回收代码

    2023-06-20 06:38:47
  • SpringBoot中自定义注解实现参数非空校验的示例

    2022-04-12 10:55:55
  • java list去重操作实现方式

    2021-09-22 13:26:08
  • Java properties 和 yml 的区别解析

    2023-04-01 22:28:09
  • asp之家 软件编程 m.aspxhome.com