A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 陈君 金牌黑马   /  2014-8-4 17:04  /  1185 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

转自:http://www.jb51.net/article/52989.htm
在很多项目中,为了安全安全考虑,需要对数据包进行加密处理,本文实例所述的即为C#加密代码,在应用开发中有很大的实用价值。说起数据包加密,其实对C#编程者来说,应该是一个基础的技巧,是进行C#程序设计人员必须要掌握的技能。
C#实现加密功能的核心代码如下:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Threading;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Net.NetworkInformation;
  13. using System.Security.Cryptography;
  14. using System.IO;
  15. namespace EncryptDataReport
  16. {
  17. public partial class Form1 : Form
  18. {
  19. public Form1()
  20. {
  21. InitializeComponent();
  22. }
  23. #region 定义全局对象及变量
  24. private IPEndPoint Server;//服务器端
  25. private IPEndPoint Client;//客户端
  26. private Socket mySocket;//套接字
  27. private EndPoint ClientIP;//IP地址
  28. byte[] buffer, data;//接收缓存
  29. bool blFlag = true;//标识是否第一次发送信息
  30. bool ISPort = false;//判断端口打开
  31. int SendNum1, ReceiveNum1, DisNum1; //记录窗体加载时的已发送\已接收\丢失的数据报
  32. int SendNum2, ReceiveNum2, DisNum2; //记录当前已发送\已接收\丢失的数据报
  33. int SendNum3, ReceiveNum3, DisNum3; //缓存已发送\已接收\丢失的数据报
  34. int port;//端口号
  35. #endregion
  36. //异步接收信息
  37. private void StartLister(IAsyncResult IAResult)
  38. {
  39. int Num = mySocket.EndReceiveFrom(IAResult, ref ClientIP);
  40. string strInfo = Encoding.Unicode.GetString(buffer, 0, Num);
  41. rtbContent.AppendText("用户" + ClientIP.ToString());
  42. rtbContent.AppendText(":");
  43. rtbContent.AppendText("\r\n");
  44. rtbContent.AppendText(DecryptDES(strInfo, "mrsoftxk"));//对接收到的信息进行解密
  45. rtbContent.AppendText("\r\n");
  46. mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ClientIP, new AsyncCallback(StartLister), null);
  47. }
  48. //初始化已发送、已接收和丢失的数据报
  49. private void Form1_Load(object sender, EventArgs e)
  50. {
  51. if (blFlag == true)
  52. {
  53. IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties();
  54. UdpStatistics myUdpStat = null;
  55. myUdpStat = NetInfo.GetUdpIPv4Statistics();
  56. SendNum1 = Int32.Parse(myUdpStat.DatagramsSent.ToString());
  57. ReceiveNum1 = Int32.Parse(myUdpStat.DatagramsReceived.ToString());
  58. DisNum1 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
  59. }
  60. }
  61. //设置端口号
  62. private void button4_Click(object sender, EventArgs e)
  63. {
  64. try
  65. {
  66. port = Convert.ToInt32(textBox4.Text);
  67. CheckForIllegalCrossThreadCalls = false;
  68. buffer = new byte[1024];
  69. data = new byte[1024];
  70. Server = new IPEndPoint(IPAddress.Any, port);
  71. Client = new IPEndPoint(IPAddress.Broadcast, port);
  72. ClientIP = (EndPoint)Server;
  73. mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  74. mySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  75. mySocket.Bind(Server);
  76. mySocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ClientIP, new AsyncCallback(StartLister), null);
  77. ISPort = true;//打开指定端口号
  78. }
  79. catch { }
  80. }
  81. //发送信息
  82. private void button2_Click(object sender, EventArgs e)
  83. {
  84. if (ISPort == true)//判断是否有打开的端口号
  85. {
  86. IPGlobalProperties NetInfo = IPGlobalProperties.GetIPGlobalProperties();
  87. UdpStatistics myUdpStat = null;
  88. myUdpStat = NetInfo.GetUdpIPv4Statistics();
  89. try
  90. {
  91. if (blFlag == false)//非第一次发送
  92. {
  93. SendNum2 = Int32.Parse(myUdpStat.DatagramsSent.ToString());
  94. ReceiveNum2 = Int32.Parse(myUdpStat.DatagramsReceived.ToString());
  95. DisNum2 = Int32.Parse(myUdpStat.IncomingDatagramsDiscarded.ToString());
  96. textBox1.Text = Convert.ToString(SendNum2 - SendNum3);
  97. textBox2.Text = Convert.ToString(ReceiveNum2 - ReceiveNum3);
  98. textBox3.Text = Convert.ToString(DisNum2 - DisNum3);
  99. }
  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. }
复制代码

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

  1. <P> </P>
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马