在很多項目中,為了安全安全考慮,需要對數據包進行加密處理,本文實例所述的即為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#實現數據包加密與解密實例詳解