예제 #1
0
        //hàm thực hiện mã hoá
        public string MaHoa(string plaintext, Khoa key, int chose)//chose=1 mã hoá, chose=-1 giải m
        {
            this.KhoaDES = key;

            KhoaDES.SinhKhoaCon();//chạy hàm tạo khoá con cho các round
            string plainText;

            if (chose == 1)                                  //nếu là mã hoá
            {
                plainText = Method.String2Binary(plaintext); //chuyển chuỗi sang nhị phân
                plainText = Method.ChinhDoDai64(plainText);  //thêm bit 0 để số bit là bội của 64
            }
            else
            {
                plainText = plaintext;
            }
            string[] pt = Method.SplitString(plainText);//chia thành mảng các chuỗi 64bit để xly

            string SauIP, left, right, F;

            string CipherText = "";

            for (int i = 0; i < pt.Length; i++)//xử lý từng khối 64bit
            {
                string temp = "";
                SauIP = Method.Permute(pt[i], initial_perm);//đưa qua hộp hoán vị đầu vào
                //chia đôi chuỗi
                left  = SauIP.Substring(0, 32);
                right = SauIP.Substring(32, 32);

                for (int j = 0; j < 16; j++)                                  //16 round của DES
                {
                    F    = HamF(right, KhoaDES.KhoaPhu[chose == 1?j:15 - j]); //tìm hàm F
                    left = Method.XOR(left, F);                               //xor left với F
                    //hoán vị
                    temp  = left;
                    left  = right;
                    right = temp;
                }
                string temp1 = "";

                //hoán vị 2 chuỗi
                temp1 += right;
                temp1 += left;

                CipherText += Method.Permute(temp1, final_perm);//đưa qua hộp hvi đầu ra
            }
            //CipherText = Method.Binary2String(CipherText);
            if (chose == -1)
            {
                CipherText = Method.CatDuLieu64(CipherText);   //loại bỏ các bit đã thêm
                CipherText = Method.Binary2String(CipherText); //đưa về kiểu string để hiển thị
            }
            return(CipherText);
        }