コード例 #1
0
ファイル: Form1.cs プロジェクト: vhp28795/finalprojectltat
        private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                int    nReceived   = sck.EndReceive(aResult);
                byte[] receiveData = null;
                receiveData = (byte[])aResult.AsyncState;
                byte[] ct = new byte[nReceived];
                Array.Copy(receiveData, 0, ct, 0, nReceived);

                byte[] pubka = new byte[72];
                Array.Copy(ct, 0, pubka, 0, 72);

                byte[] encryptedmes = new byte[ct.Length - 72];
                Array.Copy(ct, 72, encryptedmes, 0, ct.Length - 72);
                string receiveMessage = null;

                //Decrypt mess
                byte[] seck = difhel.DH1(key_pair, pubk);
                string key  = Convert.ToString(seck);
                receiveMessage = aes.Decrypt(encryptedmes, key, 256);

                //tách padding
                byte[] mesbyte = Encoding.UTF8.GetBytes(receiveMessage);
                int    length  = mesbyte.Length;
                byte[] chuoi   = new byte[length];
                while (mesbyte[length - 1] == 0x00)
                {
                    length--;
                }
                length--;
                Array.Copy(mesbyte, 0, chuoi, 0, length);

                string receivemes = System.Text.Encoding.UTF8.GetString(chuoi);

                //Adding this message into ListBox
                listBox1.Items.Add("Other: " + receivemes);

                //Show key DH & encrypt mess
                keybox.Text     = System.Convert.ToBase64String(pubk);
                seckey.Text     = System.Convert.ToBase64String(seck);
                encryptbox.Text = System.Convert.ToBase64String(encryptedmes);

                buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }