SoFunction
Updated on 2025-03-03

Detailed explanation of the C# implementation of packet encryption and decryption examples

In many projects, for security reasons, data packets need to be encrypted. The C# encryption code described in this example is the C# encryption code, which has great practical value in application development. Speaking of packet encryption, it should actually be a basic skill for C# programmers, which is a skill that C# programmers must master.

The core code for C# to implement encryption function is as follows:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
namespace EncryptDataReport
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    #region Define global objects and variables    private IPEndPoint Server;// Server side    private IPEndPoint Client;//Client    private Socket mySocket;//Socket    private EndPoint ClientIP;//IP address    byte[] buffer, data;//Receive cache    bool blFlag = true;//Identify whether the message is sent for the first time    bool ISPort = false;//Judge the port is open    int SendNum1, ReceiveNum1, DisNum1; //Record the sent\received\lost datagrams when the form is loaded    int SendNum2, ReceiveNum2, DisNum2; //Record the currently sent\received\lost datagram    int SendNum3, ReceiveNum3, DisNum3; //Cached sent\received\lost datagram    int port;//Port number    #endregion
    //Asynchronously receive information    private void StartLister(IAsyncResult IAResult)
    {
      int Num = (IAResult, ref ClientIP);
      string strInfo = (buffer, 0, Num);
      ("user" + ());
      (":");
      ("\r\n");
      (DecryptDES(strInfo, "mrsoftxk"));//Decrypt the received information      ("\r\n");
      (buffer, 0, , , ref ClientIP, new AsyncCallback(StartLister), null);
    }
    //Initialize sent, received and lost datagrams    private void Form1_Load(object sender, EventArgs e)
    {
      if (blFlag == true)
      {
        IPGlobalProperties NetInfo = ();
        UdpStatistics myUdpStat = null;
        myUdpStat = NetInfo.GetUdpIPv4Statistics();
        SendNum1 = (());
        ReceiveNum1 = (());
        DisNum1 = (());
      }
    }
    //Set the port number    private void button4_Click(object sender, EventArgs e)
    {
      try
      {
        port = Convert.ToInt32();
        CheckForIllegalCrossThreadCalls = false;
        buffer = new byte[1024];
        data = new byte[1024];
        Server = new IPEndPoint(, port);
        Client = new IPEndPoint(, port);
        ClientIP = (EndPoint)Server;
        mySocket = new Socket(, , );
        (, , 1);
        (Server);
        (buffer, 0, , , ref ClientIP, new AsyncCallback(StartLister), null);
        ISPort = true;//Open the specified port number      }
      catch { }
    }
    //Send information    private void button2_Click(object sender, EventArgs e)
    {
      if (ISPort == true)//Judge whether there is an open port number      {
        IPGlobalProperties NetInfo = ();
        UdpStatistics myUdpStat = null;
        myUdpStat = NetInfo.GetUdpIPv4Statistics();
        try
        {
          if (blFlag == false)//Not first time send          {
            SendNum2 = (());
            ReceiveNum2 = (());
            DisNum2 = (());
             = (SendNum2 - SendNum3);
             = (ReceiveNum2 - ReceiveNum3);
             = (DisNum2 - DisNum3);
          }
          SendNum2 = (());
          ReceiveNum2 = (());
          DisNum2 = (());
          SendNum3 = SendNum2; //Record this sending datagram          ReceiveNum3 = ReceiveNum2;//Record this received datagram          DisNum3 = DisNum2; //Record this lost datagram          if (blFlag == true)//First send          {
             = (SendNum2 - SendNum1);
             = (ReceiveNum2 - ReceiveNum1);
             = (DisNum2 - DisNum1);
            blFlag = false;
          }
        }
        catch (Exception ex)
        {
          (, "Prompt message", , );
        }
        string str = EncryptDES(, "mrsoftxk");//Encrypt the information to be sent        data = (str);
        (data, , , Client);
         = "";
      }
      else
      {
        ("Please open the port first!", "hint", , );
        ();
      }
    }
    //Clear the screen    private void button1_Click(object sender, EventArgs e)
    {
      ();
    }
    //quit    private void button3_Click(object sender, EventArgs e)
    {
      ();
    }
    //Press the <Ctrl+Enter> key combination to send information    private void rtbSend_KeyDown(object sender, KeyEventArgs e)
    {
      //Send a message when Ctrl and Enter are pressed at the same time      if ( &amp;&amp;  == 13)
      {
         = true;
        button2_Click(this, null);
      }
    }
    //Cha record scrolls at any time    private void rtbContent_TextChanged(object sender, EventArgs e)
    {
      ();
    }
    private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };//Key    #region DES encryption string    ///&lt;summary&gt;  
    ///DES encryption string    ///&lt;/summary&gt;  
    ///<param name="str">String to be encrypted</param>    ///<param name="key">Encryption key, required to be 8 bits</param>    ///<returns> Encryption successfully returns the encrypted string, and fails to return the source string</returns>    public string EncryptDES(string str, string key)
    {
      try
      {
        byte[] rgbKey = Encoding.((0, 8));
        byte[] rgbIV = Keys;
        byte[] inputByteArray = Encoding.(str);
        DESCryptoServiceProvider myDES = new DESCryptoServiceProvider();
        MemoryStream MStream = new MemoryStream();
        CryptoStream CStream = new CryptoStream(MStream, (rgbKey, rgbIV), );
        (inputByteArray, 0, );
        ();
        return Convert.ToBase64String(());
      }
      catch
      {
        return str;
      }
    }
    #endregion
    #region DES decryption string    ///&lt;summary&gt;  
    ///DES decryption string    ///&lt;/summary&gt;  
    ///<param name="str">String to be decrypted</param>    ///<param name="key">Decryption key, required to be 8 bits, the same as the encryption key</param>    ///<returns>The decryption successfully returns the decrypted string, and the source string is returned to the failed</returns>    public string DecryptDES(string str, string key)
    {
      try
      {
        byte[] rgbKey = Encoding.(key);
        byte[] rgbIV = Keys;
        byte[] inputByteArray = Convert.FromBase64String(str);
        DESCryptoServiceProvider myDES = new DESCryptoServiceProvider();
        MemoryStream MStream = new MemoryStream();
        CryptoStream CStream = new CryptoStream(MStream, (rgbKey, rgbIV), );
        (inputByteArray, 0, );
        ();
        return Encoding.(());
      }
      catch
      {
        return str;
      }
    }
    #endregion
  }
}

This example has detailed comments, which should not be difficult for developers to understand. Readers can improve the code of this example according to their own project needs to meet their own application needs.