A5下载 - 努力做内容最丰富最安全的下载站!

A5站长下载站

当前位置:A5下载 > 源码技巧 > 父类数据 > C#实现数据包加密与解密实例详解

C#实现数据包加密与解密实例详解

时间:2014-07-30 16:16作者:zhao人气:112

在很多项目中,为了安全安全考虑,需要对数据包进行加密处理,本文实例所述的即为C#加密代码,在应用开发中有很大的实用价值。说起数据包加密,其实对C#编程者来说,应该是一个基础的技巧,是进行C#程序设计人员必须要掌握的技能。C#实现数据包加密与解密实例详解

C#实现加密功能的核心代码如下:C#实现数据包加密与解密实例详解

001 using System;
002 using System.Collections.Generic;
003 using System.ComponentModel;
004 using System.Data;
005 using System.Drawing;
006 using System.Linq;
007 using System.Text;
008 using System.Windows.Forms;
009 using System.Threading;
010 using System.Net;
011 using System.Net.Sockets;
012 using System.Net.NetworkInformation;
013 using System.Security.Cryptography;
014 using System.IO;
015 namespace EncryptDataReport
016 {
017 public partial class Form1 : Form
018 {
019 public Form1()
020 {
021 InitializeComponent();
022 }
023 #region 定义全局对象及变量
024 private IPEndPoint Server;//服务器端
025 private IPEndPoint Client;//客户端
026 private Socket mySocket;//套接字
027 private EndPoint ClientIP;//IP地址
028 byte[] buffer, data;//接收缓存
029 bool blFlag = true;//标识是否第一次发送信息
030 bool ISPort = false;//判断端口打开
031 int SendNum1, ReceiveNum1, DisNum1; //记录窗体加载时的已发送已接收丢失的数据报
032 int SendNum2, ReceiveNum2, DisNum2; //记录当前已发送已接收丢失的数据报
033 int SendNum3, ReceiveNum3, DisNum3; //缓存已发送已接收丢失的数据报
034 int port;//端口号
035 #endregion
036 //异步接收信息
037 private void StartLister(IAsyncResult IAResult)
038 {
039 int Num = mySocket.EndReceiveFrom(IAResult, ref ClientIP);
040 string strInfo = Encoding.Unicode.GetString(buffer, 0, Num);
041 rtbContent.AppendText("用户" + ClientIP.ToString());
042 rtbContent.AppendText(":");
043 rtbContent.AppendText("rn");
044 rtbContent.AppendText(DecryptDES(strInfo, "mrsoftxk"));//对接收到的信息进行解密
045 rtbContent.AppendText("rn");
046 mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ClientIP, new AsyncCallback(StartLister), null);
047 }
048 //初始化已发送、已接收和丢失的数据报
049 private void Form1_Load(object sender, EventArgs e)
050 {
051 if (blFlag == true)
052 {
053 IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties();
054 UdpStatistics myUdpStat = null;
055 myUdpStat = NetInfo.GetUdpIPv4Statistics();
056 SendNum1 = Int32.Parse(myUdpStat.DatagramsSent.ToString());
057 ReceiveNum1 = Int32.Parse(myUdpStat.DatagramsReceived.ToString());
058 DisNum1 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
059 }
060 }
061 //设置端口号
062 private void button4_Click(object sender, EventArgs e)
063 {
064 try
065 {
066 port = Convert.ToInt32(textBox4.Text);
067 CheckForIllegalCrossThreadCalls = false;
068 buffer = new byte[1024];
069 data = new byte[1024];
070 Server = new IPEndPoint(IPAddress.Any, port);
071 Client = new IPEndPoint(IPAddress.Broadcast, port);
072 ClientIP = (EndPoint)Server;
073 mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
074 mySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
075 mySocket.Bind(Server);
076 mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ClientIP, new AsyncCallback(StartLister), null);
077 ISPort = true;//打开指定端口号
078 }
079 catch { }
080 }
081 //发送信息
082 private void button2_Click(object sender, EventArgs e)
083 {
084 if (ISPort == true)//判断是否有打开的端口号
085 {
086 IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties();
087 UdpStatistics myUdpStat = null;
088 myUdpStat = NetInfo.GetUdpIPv4Statistics();
089 try
090 {
091 if (blFlag == false)//非第一次发送
092 {
093 SendNum2 = Int32.Parse(myUdpStat.DatagramsSent.ToString());
094 ReceiveNum2 = Int32.Parse(myUdpStat.DatagramsReceived.ToString());
095 DisNum2 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
096 textBox1.Text = Convert.ToString(SendNum2 - SendNum3);
097 textBox2.Text = Convert.ToString(ReceiveNum2 - ReceiveNum3);
098 textBox3.Text = Convert.ToString(DisNum2 - DisNum3);
099 }
100 SendNum2 = Int32.Parse(myUdpStat.DatagramsSent.ToString());
101 ReceiveNum2 = Int32.Parse(myUdpStat.DatagramsReceived.ToString());
102 DisNum2 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
103 SendNum3 = SendNum2; //记录本次的发送数据报
104 ReceiveNum3 = ReceiveNum2;//记录本次的接收数据报
105 DisNum3 = DisNum2; //记录本次的丢失数据报
106 if (blFlag == true)//第一次发送
107 {
108 textBox1.Text = Convert.ToString(SendNum2 - SendNum1);
109 textBox2.Text = Convert.ToString(ReceiveNum2 - ReceiveNum1);
110 textBox3.Text = Convert.ToString(DisNum2 - DisNum1);
111 blFlag = false;
112 }
113 }
114 catch (Exception ex)
115 {
116 MessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
117 }
118 string str = EncryptDES(rtbSend.Text, "mrsoftxk");//加密要发送的信息
119 data = Encoding.Unicode.GetBytes(str);
120 mySocket.SendTo(data, data.Length, SocketFlags.None, Client);
121 rtbSend.Text = "";
122 }
123 else
124 {
125 MessageBox.Show("请首先打开端口!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
126 button4.Focus();
127 }
128 }
129 //清屏
130 private void button1_Click(object sender, EventArgs e)
131 {
132 rtbContent.Clear();
133 }
134 //退出
135 private void button3_Click(object sender, EventArgs e)
136 {
137 Application.Exit();
138 }
139 //按<Ctrl+Enter>组合键发送信息
140 private void rtbSend_KeyDown(object sender, KeyEventArgs e)
141 {
142 //当同时按下Ctrl和Enter时,发送消息
143 if (e.Control && e.KeyValue == 13)
144 {
145 e.Handled = true;
146 button2_Click(this, null);
147 }
148 }
149 //聊天记录随时滚动
150 private void rtbContent_TextChanged(object sender, EventArgs e)
151 {
152 rtbContent.ScrollToCaret();
153 }
154 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };//密钥
155 #region DES加密字符串
156 ///<summary>
157 ///DES加密字符串
158 ///</summary>
159 ///<param name="str">待加密的字符串</param>
160 ///<param name="key">加密密钥,要求为8位</param>
161 ///<returns>加密成功返回加密后的字符串,失败返回源字符串</returns>
162 public string EncryptDES(string str, string key)
163 {
164 try
165 {
166 byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
167 byte[] rgbIV = Keys;
168 byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
169 DESCryptoServiceProvider myDES = new DESCryptoServiceProvider();
170 MemoryStream MStream = new MemoryStream();
171 CryptoStream CStream = new CryptoStream(MStream, myDES.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
172 CStream.Write(inputByteArray, 0, inputByteArray.Length);
173 CStream.FlushFinalBlock();
174 return Convert.ToBase64String(MStream.ToArray());
175 }
176 catch
177 {
178 return str;
179 }
180 }
181 #endregion
182 #region DES解密字符串
183 ///<summary>
184 ///DES解密字符串
185 ///</summary>
186 ///<param name="str">待解密的字符串</param>
187 ///<param name="key">解密密钥,要求为8位,和加密密钥相同</param>
188 ///<returns>解密成功返回解密后的字符串,失败返源字符串</returns>
189 public string DecryptDES(string str, string key)
190 {
191 try
192 {
193 byte[] rgbKey = Encoding.UTF8.GetBytes(key);
194 byte[] rgbIV = Keys;
195 byte[] inputByteArray = Convert.FromBase64String(str);
196 DESCryptoServiceProvider myDES = new DESCryptoServiceProvider();
197 MemoryStream MStream = new MemoryStream();
198 CryptoStream CStream = new CryptoStream(MStream, myDES.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
199 CStream.Write(inputByteArray, 0, inputByteArray.Length);
200 CStream.FlushFinalBlock();
201 return Encoding.UTF8.GetString(MStream.ToArray());
202 }
203 catch
204 {
205 return str;
206 }
207 }
208 #endregion
209 }
210 }

 

本例备有详细的注释,对于开发者而言应该不难理解,读者可以根据自身项目需要改进本例代码以符合自身应用需求。C#实现数据包加密与解密实例详解

 

标签C#实现数据包加密与解密实例详解,C#实现数据包加密与解密

相关下载

查看所有评论+

网友评论

网友
您的评论需要经过审核才能显示

公众号