Ejemplo n.º 1
0
        public void CalculateCrc_WithZeroBytes_CrcXorsToMagicNumber()
        {
            // From section 4.4.7 ("CRC-32") of the ZIP format specification
            // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
            const uint zipCrc32MagicNumber = 0xdebb20e3;

            var bytes  = BitConverter.GetBytes(0U);
            var crc    = Crc32.CalculateCrc(bytes);
            var actual = crc ^ 0xffffffff;

            Assert.Equal(zipCrc32MagicNumber, actual);
        }
Ejemplo n.º 2
0
        public void CalculateCrc_WithDifferentInput_ReturnsDifferentCrc()
        {
            // Arrange
            var data1 = Encoding.ASCII.GetBytes("Test data1");
            var data2 = Encoding.ASCII.GetBytes("Test data2");

            // Act
            var code1 = Crc32.CalculateCrc(data1);
            var code2 = Crc32.CalculateCrc(data2);

            // Assert
            code1.Should().NotBe(code2);
        }
Ejemplo n.º 3
0
        public void CalculateCrc_WithSameInput_ReturnsSameCrc()
        {
            // Arrange
            var data = Encoding.ASCII.GetBytes("Test data");

            // Act
            var code1 = Crc32.CalculateCrc(data);
            var code2 = Crc32.CalculateCrc(data);
            var code3 = Crc32.CalculateCrc(data);

            // Assert
            code1.Should().Be(code2);
            code1.Should().Be(code3);
        }
Ejemplo n.º 4
0
        private void Crc32Menu_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog {
                Filter = "All Files|*.*"
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var data       = File.ReadAllBytes(dialog.FileName);
                var hash       = Crc32.CalculateCrc(data);
                var bytes      = BitConverter.GetBytes(hash);
                var hashString = BitConverter.ToString(bytes);
                CopyMessageBox.Show("CRC32:", hash.ToString(), "Calculated CRC32");
            }
        }
Ejemplo n.º 5
0
        private void ChangeExecutable()
        {
            var dialog = new OpenFileDialog {
                Filter = "Executable|*.exe|All Files|*.*"
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var fileName = Path.GetFileName(dialog.FileName);

                var data = File.ReadAllBytes(dialog.FileName);
                var crc  = Crc32.CalculateCrc(data);

                _movie.RealHeader.ExeName = fileName;
                _movie.RealHeader.Crc32   = crc;
                _movie.RealHeader.ExeSize = (uint)data.Length;
            }

            _tab.HeaderControl.Refresh();
        }
Ejemplo n.º 6
0
        private void BackgroundWorker_Unpacker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker unpacker = sender as BackgroundWorker;

            byte[] decode_arr   = new byte[decode_head_bytes.Count];
            int    start_adress = Adress_to_Int(textBox_Files_St_Adr.Text);

            for (int i = 0; i < decode_head_bytes.Count; i++)
            {
                decode_arr[i] = decode_head_bytes[i];
            }
            Array.Resize(ref F_I_B, (int)(H_I.Conf_Files + H_I.Bin_Files));
            char[] trim_chars = { '\0' };
            for (int i = 0; i < H_I.Conf_Files + H_I.Bin_Files; i++)                                                                                                                                           // Первый цикл из всех файлов, запакованных в прошивку
            {
                F_I_B[i].ROM_Name  = new ASCIIEncoding().GetString(decode_arr, i * (int)Functions.Parsing_Bytes.File_info + start_adress, (int)Functions.Parsing_Bytes.String_parse).TrimEnd(trim_chars);      // 0х40 (64) Имя файла прошивки
                F_I_B[i].File_Name = new ASCIIEncoding().GetString(decode_arr, i * (int)Functions.Parsing_Bytes.File_info + 64 + start_adress, (int)Functions.Parsing_Bytes.String_parse).TrimEnd(trim_chars); // 0х40 (64) Имя файла
                F_I_B[i].Offset    = BitConverter.ToInt64(decode_arr, i * (int)Functions.Parsing_Bytes.File_info + 128 + start_adress) * 512;                                                                  // 0х8 (2х4) Начальный адрес блока
                F_I_B[i].Size      = BitConverter.ToInt64(decode_arr, i * (int)Functions.Parsing_Bytes.File_info + 136 + start_adress);                                                                        // 0х8 (2х4) Размер
                F_I_B[i].CRC       = BitConverter.ToInt64(decode_arr, i * (int)Functions.Parsing_Bytes.File_info + 144 + start_adress);                                                                        // 0х8 (2х4) CRC32 Контрольная сумма
                F_I_B[i].Res       = BitConverter.ToInt64(decode_arr, i * (int)Functions.Parsing_Bytes.File_info + 152 + start_adress);                                                                        // 0х8 Резерв
                long   size_for_decode = F_I_B[i].Size;
                string path_file       = Decode_ROM_Path + "\\" + F_I_B[i].File_Name;
                while (size_for_decode % 512 != 0) // Читаем блоками по 512 байт
                {
                    size_for_decode++;
                }
                byte[] convert_bytes = new byte[size_for_decode];
                using (FileStream fs = new FileStream(e.Argument.ToString(), FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader br = new BinaryReader(fs, new ASCIIEncoding()))
                    {
                        fs.Position = F_I_B[i].Offset; // Смещение позиции чтения на начальный адрес
                        byte[] file_bytes = br.ReadBytes((int)size_for_decode);

                        if (i < H_I.Conf_Files) // Обрабатываем тут конфигурационные файлы, требующие расшифровки (идут в начале)
                        {
                            if (radioButton_Code.Checked)
                            {
                                convert_bytes = fn.Decoder(file_bytes, key_decode);
                            }
                            if (radioButton_Code_Free.Checked)
                            {
                                convert_bytes = file_bytes;
                            }
                        }
                        else // За ними бинарные файлы в чистом виде.
                        {
                            convert_bytes = file_bytes;
                        }
                    }
                }
                if (convert_bytes.Length > F_I_B[i].Size)
                {
                    Array.Resize(ref convert_bytes, (int)F_I_B[i].Size);
                }
                if (unpacker.CancellationPending || Convert.ToUInt32(F_I_B[i].CRC) != Crc32.CalculateCrc(convert_bytes)) // Проверяем контрольную сумму
                {
                    e.Cancel = true;
                    break;
                }
                using (BinaryWriter writer = new BinaryWriter(File.Open(path_file, FileMode.Create), new ASCIIEncoding()))
                {
                    writer.Write(convert_bytes);
                }
                unpacker.ReportProgress(i * 100 / (int)(H_I.Conf_Files + H_I.Bin_Files));
                Thread.Sleep(1);
            }
        }
Ejemplo n.º 7
0
        private void BackgroundWorker_unpacker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker unpacker = sender as BackgroundWorker;

            File_info_bytes[] F_I_B = new File_info_bytes[(int)(H_I.Conf_Files + H_I.Bin_Files)];                                                                                                       //Информация для одиночного файла
            int start_adress        = 0x2800;                                                                                                                                                           //Адрес начала списка файлов

            for (int i = 0; i < H_I.Conf_Files + H_I.Bin_Files; i++)                                                                                                                                    // Первый цикл из всех файлов, запакованных в прошивку
            {
                F_I_B[i].ROM_Name  = new ASCIIEncoding().GetString(decode_header_bytes, i * (int)Func.Parsing_Bytes.File_info + start_adress, (int)Func.Parsing_Bytes.String_parse).TrimEnd('\0');      // 0х40 (64) Имя файла прошивки
                F_I_B[i].File_Name = new ASCIIEncoding().GetString(decode_header_bytes, i * (int)Func.Parsing_Bytes.File_info + 64 + start_adress, (int)Func.Parsing_Bytes.String_parse).TrimEnd('\0'); // 0х40 (64) Имя файла
                F_I_B[i].Offset    = BitConverter.ToInt64(decode_header_bytes, i * (int)Func.Parsing_Bytes.File_info + 128 + start_adress) * 512;                                                       // 0х8 (2х4) Начальный адрес блока
                F_I_B[i].Size      = BitConverter.ToInt64(decode_header_bytes, i * (int)Func.Parsing_Bytes.File_info + 136 + start_adress);                                                             // 0х8 (2х4) Размер
                F_I_B[i].CRC       = BitConverter.ToInt64(decode_header_bytes, i * (int)Func.Parsing_Bytes.File_info + 144 + start_adress);                                                             // 0х8 (2х4) CRC32 Контрольная сумма
                F_I_B[i].Res       = BitConverter.ToInt64(decode_header_bytes, i * (int)Func.Parsing_Bytes.File_info + 152 + start_adress);                                                             // 0х8 Резерв
                long   size_for_decode = F_I_B[i].Size;
                string path_file       = Decode_ROM_Path + "\\" + F_I_B[i].File_Name;
                while (size_for_decode % 512 != 0) // Читаем блоками по 512 байт
                {
                    size_for_decode++;
                }
                byte[] convert_bytes = new byte[size_for_decode];
                using (BinaryReader br = new BinaryReader(File.OpenRead(ROM_File_Path)))
                {
                    br.BaseStream.Position = F_I_B[i].Offset; // Смещение позиции чтения на начальный адрес
                    byte[] file_bytes = br.ReadBytes((int)size_for_decode);
                    if (i < H_I.Conf_Files)                   // Обрабатываем тут конфигурационные файлы, требующие расшифровки (идут в начале)
                    {
                        convert_bytes = func.Decoder(file_bytes, key_decode);
                    }
                    else // За ними бинарные файлы в чистом виде.
                    {
                        convert_bytes = file_bytes;
                    }
                }
                if (convert_bytes.Length > F_I_B[i].Size)
                {
                    Array.Resize(ref convert_bytes, (int)F_I_B[i].Size);
                }
                if (unpacker.CancellationPending || Convert.ToUInt32(F_I_B[i].CRC) != Crc32.CalculateCrc(convert_bytes)) // Проверяем контрольную сумму
                {
                    e.Cancel = true;
                    break;
                }
                using (BinaryWriter writer = new BinaryWriter(File.Open(path_file, FileMode.Create), new ASCIIEncoding()))
                {
                    writer.Write(convert_bytes);
                }
                unpacker.ReportProgress(i * 100 / (int)(H_I.Conf_Files + H_I.Bin_Files), F_I_B[i]);
                Thread.Sleep(1);
            }
        }
    public byte[] SerializePacket <T>(NetworkPacket <T> packetToSerialize, bool isReliable = false, uint objectID = 0)
    {
        MemoryStream memoryStream = new MemoryStream();
        PacketHeader packetHeader = new PacketHeader();

        packetHeader.packetTypeID = (uint)packetToSerialize.type;
        packetHeader.Serialize(memoryStream);

        if (packetToSerialize.type == PacketType.User)
        {
            UserPacketHeader userPacketHeader = new UserPacketHeader();

            userPacketHeader.packetTypeID = packetToSerialize.userPacketTypeID;
            userPacketHeader.packetID     = localSequence;
            userPacketHeader.senderID     = NetworkManager.Instance.clientID;
            userPacketHeader.objectID     = objectID;
            userPacketHeader.isReliable   = isReliable;

            userPacketHeader.Serialize(memoryStream);


            ReliablePacketHeader reliablePacketHeader = new ReliablePacketHeader();

            reliablePacketHeader.sequence = localSequence;
            reliablePacketHeader.ack      = remoteSequence;

            //UnityEngine.Debug.Log("Setting up ackbits for packet Nro." + localSequence);
            ackBitfields = 0;
            for (int i = 0; i <= numberOfBitsInAck; i++)
            {
                if (sequenceNumbersReceived.Contains((uint)(remoteSequence - i)))
                {
                    //UnityEngine.Debug.Log("Sequence number is contained: " + (int)(expectedSequence - i));
                    ackBitfields |= 1 << i;
                }
            }
            //UnityEngine.Debug.Log("Ackbits to send: " + Convert.ToString(ackBitfields, 2));
            reliablePacketHeader.ackBitfield = ackBitfields;

            reliablePacketHeader.Serialize(memoryStream);
        }
        packetToSerialize.Serialize(memoryStream);

        PacketWithCrc packetWithCrc = new PacketWithCrc();

        packetWithCrc.crc        = crc32.CalculateCrc(memoryStream.ToArray());
        packetWithCrc.byteLength = memoryStream.ToArray().Length;
        packetWithCrc.data       = memoryStream.ToArray();
        memoryStream.Close();

        memoryStream = new MemoryStream();
        packetWithCrc.Serialize(memoryStream);
        memoryStream.Close();

        if (isReliable)
        {
            if (!packetsPendingToBeAcked.ContainsKey(localSequence))
            {
                packetsPendingToBeAcked.Add(localSequence, memoryStream.ToArray());
            }
        }

        return(memoryStream.ToArray());
    }