//Nhận Key và check có Đúng Hay Không public void Receive() { md5 md5 = new md5(); byte[] bytes = new byte[1024]; while (true) { int bytesRead = ns.Read(bytes, 0, bytes.Length); string text = Encoding.UTF8.GetString(bytes, 0, bytesRead); string[] s1 = text.Split(';'); switch (s1[0]) { case "Send_Key": send_key_public(s1); break; case "Receive_Key": receive_key_public(s1); break; case "Receive": if (check_md5(s1[1], s1[4])) { decrypt_mess(s1); session = true; dem = 0; } else { MessageList("Message da bi thay doi", "--"); } break; } } }
//ma hoa tin nhan public void encryptmess(string mess) { md5 md5 = new md5(); Aes256 aes256 = new Aes256(); SHA256 sha256 = SHA256Managed.Create(); //array bytes message byte[] mess1 = Encoding.UTF8.GetBytes(mess); ////array bytes key chung byte[] key1 = sha256.ComputeHash(Encoding.ASCII.GetBytes(Convert.ToString(dh.Key_Chung))); //get daytime string ivc = getdatime(); //array bytes iv from daytime , start index 2 byte[] iv = create_init_vector(ivc); txtiv.Text = Convert.ToBase64String(iv); //get 32 byte from datime for padding byte[] dayhash = sha256.ComputeHash(Encoding.ASCII.GetBytes(ivc)); //encrypt message string encrypt = aes256.EncryptString(mess1, key1, iv, dayhash); string[] enc1 = encrypt.Split(';'); string mess_md5 = md5.GetMD5(enc1[0] + Convert.ToString(dh.Key_Chung)); //byte[] enc = Encoding.ASCII.GetBytes(encrypt); string messsend = "Receive;" + encrypt + ";" + ivc + ";" + mess_md5; //string[] s1 = messsend.Split(';'); //textBoxmessnoise.Text = s1[1].ToString() + ";" + s1[2].ToString() + ";" + s1[3].ToString(); txtmessnoise.Text = messsend; senddata(messsend); }
//Check MD5,phat hien thay doi key public bool check_md5(string encrypt, string md5_encrypt) { bool check = false;//sai hien thong bao. md5 md5 = new md5(); string result = md5.GetMD5(encrypt + Convert.ToString(dh.Key_Chung)); if (result == md5_encrypt) { check = true;//dung tiep tuc gui. } return(check); }
//Tính Padding public string tinhpading(string text) { md5 hash = new md5(); string ivc = getdatime(); string chuoipading; int i = 0; int n = text.Length % 16; if (n != 0) { string thempading = hash.GetMD5(ivc).Substring(0, 16 - n); chuoipading = text + thempading; } else { chuoipading = text; } return(chuoipading); }