void Connect() { IP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { client.Connect(IP); } catch { MessageBox.Show("Không thể kết nối tới server", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } byte[] nhandodai = new byte[1024]; client.Receive(nhandodai); nhankey = new byte[BitConverter.ToInt32(nhandodai, 0)]; client.Receive(nhankey); keypublic = Convert.ToBase64String(nhankey); txtkeyserver.Text = keypublic; TaoKey(); Diff.LayKhoaBiMat(nhankey); khoabimat = Diff.aes.Key; keysecret = Convert.ToBase64String(khoabimat); txtFinalKey.Text = keysecret; byte[] laydodai = BitConverter.GetBytes(khoapublic.Length); client.Send(laydodai); byte[] Keypublic = khoapublic; client.Send(Keypublic); Thread listen = new Thread(Receive); listen.IsBackground = true; listen.Start(); }
void Receive() { try { c : while (true) { byte[] data = new byte[1024]; client.Receive(data); if (string.Equals(Encoding.UTF8.GetString(data), "guikey", StringComparison.InvariantCultureIgnoreCase)) { txtServerKey.Clear(); txtFinalKey.Clear(); nhankeydadoi = new byte[140]; client.Receive(nhankeydadoi); keypublic = Convert.ToBase64String(nhankeydadoi); txtServerKey.Text = keypublic; CreatePublicKey(); Diff.LayKhoaBiMat(nhankeydadoi); khoabimat = Diff.aes.Key; keysecret = Convert.ToBase64String(khoabimat); txtFinalKey.Text = keysecret; nhankey = nhankeydadoi; guilaipublickey(); } else if (string.Equals(Encoding.UTF8.GetString(data), "guikeytoclient", StringComparison.InvariantCultureIgnoreCase)) { txtServerKey.Clear(); txtFinalKey.Clear(); nhankeydadoi = new byte[140]; client.Receive(nhankeydadoi); keypublic = Convert.ToBase64String(nhankeydadoi); txtServerKey.Text = keypublic; Diff.LayKhoaBiMat(nhankeydadoi); khoabimat = Diff.aes.Key; keysecret = Convert.ToBase64String(khoabimat); txtFinalKey.Text = keysecret; nhankey = nhankeydadoi; } else { tinnhan = new byte[BitConverter.ToInt32(data, 0)]; client.Receive(tinnhan); byte[] nhanvector = new byte[16]; client.Receive(nhanvector); string message = Diff.GiaiMaDiffie(nhankey, tinnhan, nhanvector); dateTimeIV = md5.maHoaMd5(DateTime.Now.ToString()); string time = dateTimeIV.Substring(0, 16); dateTimeIv = Encoding.UTF8.GetBytes(time); string a = txtFinalKey.Text.Substring(0, 32); byte[] key = Encoding.ASCII.GetBytes(a); string s = aes.DecryptString(message, key, dateTimeIv); foreach (char c in s) { if (c.ToString() == ";") { string[] tokens = s.Trim().Split(';'); compare1 = tokens[1]; compare2 = md5.maHoaMd5(tokens[0]); if (compare1 != compare2) { LstMS.Items.Add("Server: " + tokens[0]); LstMS.Items.Add("Dữ liệu đã bị thay đổi trong quá trình chuyền:"); LstMS.Items.Add("Chuỗi mã trước:" + compare1); LstMS.Items.Add("Chuỗi mã sau:" + compare2); goto c; } } } LstMS.Items.Add("Server: " + s); } } }catch { Close(); } }