直播app開發搭建,將聊天資料傳送加密

zhibo系統開發發表於2023-01-06

直播app開發搭建,將聊天資料傳送加密

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    #region 定義全域性物件及變數
    private IPEndPoint Server;//伺服器端
    private IPEndPoint Client;//客戶端
    private Socket mySocket;//套接字
    private EndPoint ClientIP;//IP地址
    byte[] buffer, data;//接收快取
    bool blFlag = true;//標識是否第一次傳送資訊
    bool ISPort = false;//判斷埠開啟
    int SendNum1, ReceiveNum1, DisNum1; //記錄窗體載入時的已傳送\已接收\丟失的資料包
    int SendNum2, ReceiveNum2, DisNum2; //記錄當前已傳送\已接收\丟失的資料包
    int SendNum3, ReceiveNum3, DisNum3; //快取已傳送\已接收\丟失的資料包
    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);
    }
    //初始化已傳送、已接收和丟失的資料包
    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());
        }
    }
    //設定埠號
    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 { }
    }
    //傳送資訊
    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)//非第一次傳送
                {
                    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; //記錄本次的傳送資料包
                ReceiveNum3 = ReceiveNum2;//記錄本次的接收資料包
                DisNum3 = DisNum2; //記錄本次的丟失資料包
                if (blFlag == true)//第一次傳送
                {
                    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");//加密要傳送的資訊
            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>組合鍵傳送資訊
    private void rtbSend_KeyDown(object sender, KeyEventArgs e)
    {
        //當同時按下Ctrl和Enter時,傳送訊息
        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
}


以上就是 直播app開發搭建,將聊天資料傳送加密,更多內容歡迎關注之後的文章


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69978258/viewspace-2931126/,如需轉載,請註明出處,否則將追究法律責任。

相關文章