欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實現(xiàn)數(shù)據(jù)包加密與解密實例詳解

 更新時間:2014年07月30日 12:01:03   投稿:shichen2014  
這篇文章主要介紹了C#實現(xiàn)數(shù)據(jù)包加密與解密的方法,是一項很實用的技能,需要的朋友可以參考下

在很多項目中,為了安全安全考慮,需要對數(shù)據(jù)包進行加密處理,本文實例所述的即為C#加密代碼,在應(yīng)用開發(fā)中有很大的實用價值。說起數(shù)據(jù)包加密,其實對C#編程者來說,應(yīng)該是一個基礎(chǔ)的技巧,是進行C#程序設(shè)計人員必須要掌握的技能。

C#實現(xiàn)加密功能的核心代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.IO;
namespace EncryptDataReport
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    #region 定義全局對象及變量
    private IPEndPoint Server;//服務(wù)器端
    private IPEndPoint Client;//客戶端
    private Socket mySocket;//套接字
    private EndPoint ClientIP;//IP地址
    byte[] buffer, data;//接收緩存
    bool blFlag = true;//標識是否第一次發(fā)送信息
    bool ISPort = false;//判斷端口打開
    int SendNum1, ReceiveNum1, DisNum1; //記錄窗體加載時的已發(fā)送\已接收\丟失的數(shù)據(jù)報
    int SendNum2, ReceiveNum2, DisNum2; //記錄當前已發(fā)送\已接收\丟失的數(shù)據(jù)報
    int SendNum3, ReceiveNum3, DisNum3; //緩存已發(fā)送\已接收\丟失的數(shù)據(jù)報
    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);
    }
    //初始化已發(fā)送、已接收和丟失的數(shù)據(jù)報
    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è)置端口號
    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 { }
    }
    //發(fā)送信息
    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)//非第一次發(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ù)報
          ReceiveNum3 = ReceiveNum2;//記錄本次的接收數(shù)據(jù)報
          DisNum3 = DisNum2; //記錄本次的丟失數(shù)據(jù)報
          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("請首先打開端口!", "提示", 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)
    {
      //當同時按下Ctrl和Enter時,發(fā)送消息
      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
  }
}

本例備有詳細的注釋,對于開發(fā)者而言應(yīng)該不難理解,讀者可以根據(jù)自身項目需要改進本例代碼以符合自身應(yīng)用需求。

相關(guān)文章

最新評論