Calculate() публичный статический Метод

public static Calculate ( string text ) : UInt32
text string
Результат System.UInt32
Пример #1
0
        /// <inheritdoc/>
        public byte[] Read(IDataStorerEntry entry)
        {
            Validation.NotNull("Entry", entry);

            ZipReadOnlyStorerEntry zip64Entry = entry as ZipReadOnlyStorerEntry;

            if (zip64Entry == null)
            {
                throw new InvalidEntryException(entry.Path);
            }

            byte[] data  = null;
            int    count = (int)zip64Entry.Size;

            if (zip64Entry.CompressionMethod == CompressionMethod.Store)
            {
                data = new byte[count];
                Buffer.BlockCopy(this.zipFileData, (int)zip64Entry.FileOffset, data, 0, count);
            }
            else
            {
                data = ZLibUtils.Inflate(this.zipFileData, (int)zip64Entry.FileOffset, (int)zip64Entry.CompressedSize, count);
            }

            if (zip64Entry.CRC32 != CRC32.Calculate(data))
            {
                throw new InvalidEntryException(entry.Path);
            }

            return(data);
        }
Пример #2
0
        public static UDPPackage Parse(byte[] bytes)
        {
            Stream       stream   = new MemoryStream(bytes);
            BinaryReader reader   = new BinaryReader(stream);
            uint         crc      = reader.ReadUInt32();
            uint         checkCRC = CRC32.Calculate(reader.ReadBytes(bytes.Length - 4));

            if (crc != checkCRC)
            {
                return(new UDPPackage());                 //пакет битый
            }
            stream.Position = 4;
            uint      sign  = reader.ReadUInt32();
            ushort    parts = reader.ReadUInt16();
            BytesList body  = new BytesList();

            if (parts == 0)
            {
                body.Add(reader.ReadBytes(bytes.Length - 4 - 4 - 2));
                return(new UDPPackage(body, sign));
            }
            else
            {
                ushort part           = reader.ReadUInt16();
                ushort partsPackageId = reader.ReadUInt16();
                body.Add(reader.ReadBytes(bytes.Length - 4 - 4 - 2 - 2 - 2));
                return(new UDPPackage(partsPackageId, parts, part, body, sign));
            }
        }
Пример #3
0
 public void Calculate_Set1_Stream()
 {
     using (Stream stream = new MemoryStream(_testByteArray_1))
     {
         string result = CRC32.Calculate(stream);
         Assert.AreEqual(_crc32StringResult_1, result);
     }
 }
Пример #4
0
        public static uint HashFilename(string name, PackageHashType type)
        {
            var padding      = name.Length % 4 != 0 ? 4 - name.Length % 4 : 0;
            var paddedLength = name.Length + padding;

            // Avoid stack overflows by only allocating small buffers on the stack, and larger ones on the heap.
            // 64 chars covers most real filenames.
            var upperPaddedName = paddedLength < 64 ? stackalloc char[paddedLength] : new char[paddedLength];

            name.AsSpan().ToUpperInvariant(upperPaddedName);

            switch (type)
            {
            case PackageHashType.Classic:
            {
                for (var p = 0; p < padding; p++)
                {
                    upperPaddedName[paddedLength - 1 - p] = '\0';
                }

                var asciiBytes = paddedLength < 64 ? stackalloc byte[paddedLength] : new byte[paddedLength];
                Encoding.ASCII.GetBytes(upperPaddedName, asciiBytes);

                var data   = MemoryMarshal.Cast <byte, uint>(asciiBytes);
                var result = 0u;
                foreach (var next in data)
                {
                    result = ((result << 1) | (result >> 31)) + next;
                }

                return(result);
            }

            case PackageHashType.CRC32:
            {
                var length = name.Length;
                var lengthRoundedDownToFour = length / 4 * 4;
                if (length != lengthRoundedDownToFour)
                {
                    upperPaddedName[length] = (char)(length - lengthRoundedDownToFour);
                    for (var p = 1; p < padding; p++)
                    {
                        upperPaddedName[length + p] = upperPaddedName[lengthRoundedDownToFour];
                    }
                }

                var asciiBytes = paddedLength < 64 ? stackalloc byte[paddedLength] : new byte[paddedLength];
                Encoding.ASCII.GetBytes(upperPaddedName, asciiBytes);

                return(CRC32.Calculate(asciiBytes));
            }

            default: throw new NotImplementedException($"Unknown hash type `{type}`");
            }
        }
Пример #5
0
        public void TestCRC32()
        {
            CRC32 crc32 = new CRC32();

            UInt32[] data     = Byte2Uint32(new byte[] { 0x7E, 0x05, 0x00, 105, 16, 1, 14, 0 }, 0, 8);
            UInt32   crcValue = crc32.Calculate(data, data.Length);
            UInt32   bt0      = (crcValue & 0xFF);
            UInt32   bt1      = ((crcValue >> 8) & 0xFF);
            UInt32   bt2      = ((crcValue >> 16) & 0xFF);
            UInt32   bt3      = ((crcValue >> 24) & 0xFF);
        }
Пример #6
0
        private bool DetectTurboGECD()
        {
            //approach taken from mednafen DetectGECD()

            //check for appropriate structure
            var toc = _disc.TOC;

            if (toc.FirstRecordedTrackNumber != 1)
            {
                return(false);
            }
            if (!toc.TOCItems[1].IsData)
            {
                return(false);
            }

            //some have a signature
            if (StringAt("HACKER CD ROM SYSTEM", 0x8, 0x10))
            {
                return(true);
            }

            //some are more confusing
            if (!StringAt("CD001", 0x1, 0x10))
            {
                return(false);
            }

            byte[] sector20 = ReadDataSectorCached(20);
            var    zecrc    = CRC32.Calculate(sector20);

            //known_crcs
            if (zecrc == 0xd7b47c06)
            {
                return(true);                                 // AV Tanjou
            }
            if (zecrc == 0x86aec522)
            {
                return(true);                                 // Bishoujo Jyanshi [...]
            }
            if (zecrc == 0xc8d1b5ef)
            {
                return(true);                                 // CD Bishoujo [...]
            }
            if (zecrc == 0x0bdbde64)
            {
                return(true);                                 // CD Pachisuro [...]
            }
            return(false);
        }
Пример #7
0
        public void Calculate_Set1_Path()
        {
            string path = PathUtils.GetTempFileName(".txt");

            File.WriteAllText(path, _testString_1);
            try
            {
                string result = CRC32.Calculate(new FileInfo(path));
                Assert.AreEqual(_crc32StringResult_1, result);
            }
            finally
            {
                File.Delete(path);
            }
        }
Пример #8
0
        public UDPPackage(BytesList body, UInt32 sign = 0)
        {
            this.Body = body;
            this.Sign = sign;

            BytesList preCRCData = new BytesList();

            preCRCData.AddUInt(this.Sign);
            preCRCData.AddUShort(this.Parts);//==0
            preCRCData.Add(body);

            this.CRC = CRC32.Calculate(preCRCData);
            this.FullData.AddUInt(this.CRC);
            this.FullData.Add(preCRCData);
        }
Пример #9
0
        /// <summary>
        /// Convert command to byte array.
        /// </summary>
        /// <returns></returns>
        public byte[] ToArray()
        {
            // generate byte array of the payload.
            var payload = GeneratePayload();

            if (payload.Length > LEN_MAX_PAYLOAD)
            {
                throw new InvalidDataException("the length of the payload is out-of-range.");
            }

            byte[] output = null;
            using (MemoryStream mem = new MemoryStream())
            {
                using (BinaryWriter wr = new BinaryWriter(mem))
                {
                    // write package header (uint8).
                    wr.Write(HEADER);

                    // write package length (uint16).
                    wr.Write((UInt16)(payload.Length + LEN_API_ID + LEN_FRAME_ID + LEN_COMMAND));

                    // write API Identifier
                    wr.Write(API_IDENTIFIER_COMMAND);

                    // write frame ID
                    wr.Write(FrameID);

                    // write command (uint8).
                    wr.Write((byte)this.Command);

                    // write payload.
                    if (payload.Length > 0)
                    {
                        wr.Write(payload);
                    }

                    // calculate CRC32 of the package.
                    var   pack   = mem.ToArray();
                    CRC32 crc    = new CRC32();
                    var   crcval = crc.Calculate(pack, pack.Length);
                    wr.Write(crcval);
                }

                output = mem.ToArray();
            }

            return(output);
        }
Пример #10
0
        public static uint HashFilename(string name, PackageHashType type)
        {
            switch (type)
            {
            case PackageHashType.Classic:
            {
                name = name.ToUpperInvariant();
                if (name.Length % 4 != 0)
                {
                    name = name.PadRight(name.Length + (4 - name.Length % 4), '\0');
                }

                using (var ms = new MemoryStream(Encoding.ASCII.GetBytes(name)))
                {
                    var  len    = name.Length >> 2;
                    uint result = 0;

                    while (len-- != 0)
                    {
                        result = ((result << 1) | (result >> 31)) + ms.ReadUInt32();
                    }

                    return(result);
                }
            }

            case PackageHashType.CRC32:
            {
                name = name.ToUpperInvariant();
                var l = name.Length;
                var a = l >> 2;
                if ((l & 3) != 0)
                {
                    name += (char)(l - (a << 2));
                    var i = 3 - (l & 3);
                    while (i-- != 0)
                    {
                        name += name[a << 2];
                    }
                }

                return(CRC32.Calculate(Encoding.ASCII.GetBytes(name)));
            }

            default: throw new NotImplementedException("Unknown hash type `{0}`".F(type));
            }
        }
Пример #11
0
        private static byte[] ReadChunkData(Stream stream, int length, string type)
        {
            byte[] data = new byte[length];
            if (stream.Read(data, 0, data.Length) != data.Length)
                throw new MetaParseException($"Unable to read full PNG chunk \"{type}\" data");

            byte[] crc32 = new byte[4];
            if (stream.Read(crc32, 0, crc32.Length) != crc32.Length)
                throw new MetaParseException($"Unable to read full PNG chunk \"{type}\" CRC32");

            byte[] crcData = type.Select(c => (byte)c).Concat(data).ToArray();
            uint calculated = CRC32.Calculate(crcData, 0, crcData.Length, 0);
            uint given = BitConverter.ToUInt32(crc32.Reverse().ToArray(), 0);
            if (calculated != given)
                throw new MetaParseException($"Checksum verification failure of PNG chunk \"{type}\"");
            return data;
        }
Пример #12
0
        public static uint HashFilename(string name, PackageHashType type)
        {
            switch (type)
            {
            case PackageHashType.Classic:
            {
                name = name.ToUpperInvariant();
                if (name.Length % 4 != 0)
                {
                    name = name.PadRight(name.Length + (4 - name.Length % 4), '\0');
                }

                var result = 0u;
                var data   = Encoding.ASCII.GetBytes(name);
                var i      = 0;
                while (i < data.Length)
                {
                    var next = (uint)(data[i++] | data[i++] << 8 | data[i++] << 16 | data[i++] << 24);
                    result = ((result << 1) | (result >> 31)) + next;
                }

                return(result);
            }

            case PackageHashType.CRC32:
            {
                name = name.ToUpperInvariant();
                var l = name.Length;
                var a = l >> 2;
                if ((l & 3) != 0)
                {
                    name += (char)(l - (a << 2));
                    var i = 3 - (l & 3);
                    while (i-- != 0)
                    {
                        name += name[a << 2];
                    }
                }

                return(CRC32.Calculate(Encoding.ASCII.GetBytes(name)));
            }

            default: throw new NotImplementedException($"Unknown hash type `{type}`");
            }
        }
Пример #13
0
        public void BufferStressTest()
        {
            var r = new Random(8675309);

            using var zw = new ZwinderBuffer(new RewindConfig
            {
                BufferSize        = 1,
                TargetFrameLength = 1
            });
            var buff = new byte[40000];

            for (int round = 0; round < 10; round++)
            {
                for (int i = 0; i < 500; i++)
                {
                    zw.Capture(i, s =>
                    {
                        var length = r.Next(40000);
                        var bw     = new BinaryWriter(s);
                        var bytes  = buff.AsSpan(0, length);
                        r.NextBytes(bytes);
                        bw.Write(length);
                        bw.Write(bytes);
                        bw.Write(CRC32.Calculate(bytes));
                    });
                }
                for (int i = 0; i < zw.Count; i++)
                {
                    var info   = zw.GetState(i);
                    var s      = info.GetReadStream();
                    var br     = new BinaryReader(s);
                    var length = info.Size;
                    if (length != br.ReadInt32() + 8)
                    {
                        throw new Exception("Length field corrupted");
                    }
                    var bytes = buff.AsSpan(0, length - 8);
                    br.Read(bytes);
                    if (br.ReadUInt32() != CRC32.Calculate(bytes))
                    {
                        throw new Exception("Data or CRC field corrupted");
                    }
                }
            }
        }
Пример #14
0
        public void CompressCallback(object threadContext)
        {
            var context = (WriterThreadContext)threadContext;

            while (QueuedChunks.Count > 0)
            {
                bool result = QueuedChunks.TryDequeue(out var chunk, 250);

                if (!result)
                {
                    continue;
                }

                using (MemoryStream mem = new MemoryStream())
                {
                    foreach (var file in chunk.Value)
                    {
                        using (Stream fileStream = file.GetStream())
                            fileStream.CopyTo(mem);
                    }

                    mem.Position = 0;

                    using (Stream compressedBuffer = context.Compressor.GetStream(mem))
                    {
                        chunk.Key.Crc32            = CRC32.Calculate(compressedBuffer);
                        chunk.Key.CompressedLength = (ulong)compressedBuffer.Length;
                        compressedBuffer.Position  = 0;

                        lock (context.ArchiveStream)
                        {
                            chunk.Key.Offset = (ulong)context.ArchiveStream.Position;

                            compressedBuffer.CopyTo(context.ArchiveStream);
                        }
                    }
                }

                //Aggressive GC collections
                GC.Collect();
            }
        }
Пример #15
0
        public UDPPackage(ushort partsPackageId, ushort parts, ushort part, BytesList body, UInt32 sign = 0)
        {
            this.PartsPackageId = partsPackageId;
            this.Parts          = parts;
            this.Part           = part;
            this.Body           = body;
            this.Sign           = sign;

            BytesList preCRCData = new BytesList();

            preCRCData.AddUInt(this.Sign);
            preCRCData.AddUShort(this.Parts);//!=0
            preCRCData.AddUShort(this.Part);
            preCRCData.AddUShort(this.PartsPackageId);
            preCRCData.Add(body);

            this.CRC = CRC32.Calculate(preCRCData);
            this.FullData.AddUInt(this.CRC);
            this.FullData.Add(preCRCData);
        }
Пример #16
0
        private void Comport_DataReceived1(object sender, SerialDataReceivedEventArgs e)
        {
            int Len = Sp.BytesToRead;

            for (int i = 0; i < Len; i++)
            {
                byte bt = (byte)Sp.ReadByte();
                FrameRecvByteQueue.Enqueue(bt);
            }

            while (FrameRecvByteQueue.Count > 0)
            {
                byte bt = FrameRecvByteQueue.Dequeue();
                if (bt == PACKAGE_HEADER && TempList.Count == 0)
                {
                    TempList.Add(bt);
                    continue;
                }
                if (TempList.Count > 0) //说明发现了包
                {
                    TempList.Add(bt);
                    if (TempList.Count == 3)
                    {
                        ExpectLength = TempList[1] + TempList[2] * 256;
                    }
                    else if (TempList.Count >= (7 + ExpectLength))
                    {
                        byte[] dataList  = TempList.ToArray();
                        UInt32 Crc32     = (UInt32)(dataList[dataList.Length - 4] + (dataList[dataList.Length - 3] << 8) + (dataList[dataList.Length - 2] << 16) + (dataList[dataList.Length - 1] << 24));
                        UInt32 CalcCrc32 = Crc32Instance.Calculate(dataList, 0, dataList.Length - 4);

                        if (Crc32 == CalcCrc32) //校验成功
                        {
                            ProcessPackage(dataList);
                        }
                        ExpectLength = 0;
                        TempList     = new List <byte>();
                    }
                }
            }
        }
Пример #17
0
 public void CRC32_1Arg_Checksum()
 {
     Assert.AreEqual(64128641, CRC32.Calculate(ArrayUtils.CreateArray((byte)255, 100)));
 }
Пример #18
0
 public void Submit(string statName, int statValue)
 {
     Submit((int)CRC32.Calculate(statName), statValue);
 }
Пример #19
0
 public void CRC32_4Args_Checksum()
 {
     byte[] data = ArrayUtils.CreateArray((byte)255, 100);
     Assert.AreEqual(2307493135, CRC32.Calculate(data, data, data, data));
 }
Пример #20
0
        public void Calculate_Set2_ByteArray()
        {
            string result = CRC32.Calculate(_testByteArray_2);

            Assert.AreEqual(_crc32StringResult_2, result);
        }
Пример #21
0
        public void Flush()
        {
            var fullSaveName = SavePath + Path.DirectorySeparatorChar + SaveName + SaveExtension;

            _saveFile   = new FileStream(fullSaveName, FileMode.OpenOrCreate);
            _saveWriter = new BinaryWriter(_saveFile);
            switch (SaveType)
            {
            case SaveType.DoubutsuNoMoriPlus:
            case SaveType.AnimalCrossing:
            case SaveType.DoubutsuNoMoriEPlus:
            case SaveType.AnimalForestEPlus:
                Write(SaveDataStartOffset + SaveInfo.SaveOffsets.Checksum,
                      new UInt16BEChecksum().Calculate(
                          SaveData.Skip(SaveDataStartOffset).Take(SaveInfo.SaveOffsets.SaveSize).ToArray(),
                          (uint)SaveInfo.SaveOffsets.Checksum), IsBigEndian);

                SaveData.Skip(SaveDataStartOffset).Take(SaveInfo.SaveOffsets.SaveSize).ToArray().CopyTo(
                    SaveData,
                    SaveDataStartOffset + SaveInfo.SaveOffsets.SaveSize);
                break;

            case SaveType.WildWorld:
                Write(SaveDataStartOffset + SaveInfo.SaveOffsets.Checksum,
                      new UInt16LEChecksum().Calculate(
                          SaveData.Skip(SaveDataStartOffset).Take(SaveInfo.SaveOffsets.SaveSize).ToArray(),
                          (uint)SaveInfo.SaveOffsets.Checksum), IsBigEndian);

                SaveData.Skip(SaveDataStartOffset).Take(SaveInfo.SaveOffsets.SaveSize).ToArray().CopyTo(
                    SaveData,
                    SaveDataStartOffset + SaveInfo.SaveOffsets.SaveSize);
                break;

            case SaveType.DoubutsuNoMori:
            case SaveType.DongwuSenlin:
                Write(SaveDataStartOffset + SaveInfo.SaveOffsets.Checksum,
                      new UInt16BEChecksum().Calculate(
                          SaveData.Skip(SaveDataStartOffset).Take(0xF980).ToArray(),
                          (uint)SaveInfo.SaveOffsets.Checksum), IsBigEndian);

                SaveData.Skip(SaveDataStartOffset).Take(SaveInfo.SaveOffsets.SaveSize).ToArray().CopyTo(
                    SaveData,
                    SaveDataStartOffset + SaveInfo.SaveOffsets.SaveSize);
                break;

            case SaveType.CityFolk:
                var crc32 = new CRC32();
                for (var i = 0; i < 4; i++)
                {
                    var playerDataOffset = SaveDataStartOffset + i * 0x86C0 + 0x1140;
                    var playerCrc32      =
                        crc32.Calculate(SaveData.Skip(playerDataOffset + 4).Take(0x759C).ToArray());
                    Write(playerDataOffset, playerCrc32, true);
                }

                Write(SaveDataStartOffset + 0x5EC60,
                      crc32.Calculate(SaveData.Skip(SaveDataStartOffset + 0x5EC64).Take(0x1497C).ToArray()),
                      true);
                Write(SaveDataStartOffset + 0x5EB04,
                      crc32.Calculate(SaveData.Skip(SaveDataStartOffset + 0x5EB08).Take(0x152).ToArray(),
                                      0x12141018), true);
                Write(SaveDataStartOffset + 0x73600,
                      crc32.Calculate(SaveData.Skip(SaveDataStartOffset + 0x73604).Take(0x19BD1C).ToArray()),
                      true);
                Write(SaveDataStartOffset,
                      crc32.Calculate(SaveData.Skip(SaveDataStartOffset + 4).Take(0x1C).ToArray()), true);
                Write(SaveDataStartOffset + 0x20,
                      crc32.Calculate(SaveData.Skip(SaveDataStartOffset + 0x24).Take(0x111C).ToArray()), true);
                break;

            case SaveType.NewLeaf:
                var crc32Reflected = new NewLeafCRC32Reflected();

                Write(SaveDataStartOffset,
                      crc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 4).Take(0x1C).ToArray()));
                for (var i = 0; i < 4; i++)
                {
                    var dataOffset = SaveDataStartOffset + 0x20 + i * 0x9F10;
                    Write(dataOffset,
                          crc32Reflected.Calculate(SaveData.Skip(dataOffset + 4).Take(0x6B64).ToArray()));

                    var dataOffset2 = SaveDataStartOffset + 0x20 + 0x6B68 + i * 0x9F10;
                    Write(dataOffset2,
                          crc32Reflected.Calculate(SaveData.Skip(dataOffset2 + 4).Take(0x33A4).ToArray()));
                }

                Write(SaveDataStartOffset + 0x27C60,
                      crc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x27C60 + 4).Take(0x218B0)
                                               .ToArray()));
                Write(SaveDataStartOffset + 0x49520,
                      crc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x49520 + 4).Take(0x44B8)
                                               .ToArray()));
                Write(SaveDataStartOffset + 0x4D9DC,
                      crc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x4D9DC + 4).Take(0x1E420)
                                               .ToArray()));
                Write(SaveDataStartOffset + 0x6BE00,
                      crc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x6BE00 + 4).Take(0x20)
                                               .ToArray()));
                Write(SaveDataStartOffset + 0x6BE24,
                      crc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x6BE24 + 4).Take(0x13AF8)
                                               .ToArray()));
                break;

            case SaveType.WelcomeAmiibo:
                var wCrc32Reflected = new NewLeafCRC32Reflected();
                var wCrc32Normal    = new NewLeafCRC32Normal();

                // Reflected CRC32 Implementation Checksums
                Write(SaveDataStartOffset,
                      wCrc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 4).Take(0x1C).ToArray()));
                for (var i = 0; i < 4; i++)
                {
                    var dataOffset = SaveDataStartOffset + 0x20 + i * 0xA480;
                    Write(dataOffset,
                          wCrc32Reflected.Calculate(SaveData.Skip(dataOffset + 4).Take(0x6B84).ToArray()));

                    var dataOffset2 = SaveDataStartOffset + 0x20 + 0x6B88 + i * 0xA480;
                    Write(dataOffset2,
                          wCrc32Reflected.Calculate(SaveData.Skip(dataOffset2 + 4).Take(0x38F4).ToArray()));
                }

                Write(SaveDataStartOffset + 0x29220,
                      wCrc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x29220 + 4).Take(0x22BC8)
                                                .ToArray()));
                Write(SaveDataStartOffset + 0x4BE00,
                      wCrc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x4BE00 + 4).Take(0x44B8)
                                                .ToArray()));
                Write(SaveDataStartOffset + 0x533A4,
                      wCrc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x533A4 + 4).Take(0x1E4D8)
                                                .ToArray()));
                Write(SaveDataStartOffset + 0x71880,
                      wCrc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x71880 + 4).Take(0x20)
                                                .ToArray()));
                Write(SaveDataStartOffset + 0x718A4,
                      wCrc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x718A4 + 4).Take(0xBE4)
                                                .ToArray()));
                Write(SaveDataStartOffset + 0x738D4,
                      wCrc32Reflected.Calculate(SaveData.Skip(SaveDataStartOffset + 0x738D4 + 4).Take(0x16188)
                                                .ToArray()));

                // Normal CRC32 Implementation Checksums
                Write(SaveDataStartOffset + 0x502BC,
                      wCrc32Normal.Calculate(SaveData.Skip(SaveDataStartOffset + 0x502BC + 4).Take(0x28F0)
                                             .ToArray()));
                Write(SaveDataStartOffset + 0x52BB0,
                      wCrc32Normal.Calculate(SaveData.Skip(SaveDataStartOffset + 0x52BB0 + 4).Take(0x7F0)
                                             .ToArray()));
                Write(SaveDataStartOffset + 0x7248C,
                      wCrc32Normal.Calculate(SaveData.Skip(SaveDataStartOffset + 0x7248C + 4).Take(0x1444)
                                             .ToArray()));
                break;
            }

            _saveWriter.Write(SaveType == SaveType.DoubutsuNoMori && _byteswap
                ? SaveDataManager.ByteSwap(SaveData)
                : SaveData); // Doubutsu no Mori is dword byteswapped
            _saveWriter.Flush();
            _saveFile.Flush();

            _saveWriter.Close();
            _saveFile.Close();
            _saveWriter.Dispose();
            _saveFile.Dispose();
            ChangesMade = false;
        }
Пример #22
0
 public static uint CalculateHash(byte[] Data)
 {
     return(crc.Calculate(Data));
 }
Пример #23
0
 public void AddDefinition(string statName, string description, StatisticType type)
 {
     AddDefinition((int)CRC32.Calculate(statName), description, type);
 }
Пример #24
0
 public void Calculate_Stream_Null()
 {
     Assert.Throws <ArgumentNullException>(() => CRC32.Calculate((Stream)null));
 }
Пример #25
0
 public void Calculate_Path_Null()
 {
     Assert.Throws <ArgumentNullException>(() => CRC32.Calculate((FileInfo)null));
 }
Пример #26
0
 public void Calculate_ByteArray_Null()
 {
     Assert.Throws <ArgumentNullException>(() => CRC32.Calculate((byte[])null));
 }
Пример #27
0
 static string Hash_CRC32(byte[] data) => $"{CRC32.Calculate(data):X8}";
Пример #28
0
        /// <inheritdoc/>
        public IDataStorerEntry Add(string path, params byte[] data)
        {
            Validation.NotNull("Path", path);
            Validation.NotNull("Data", data);

            string normalizedPath = path.Replace('\\', '/');

            int pos = normalizedPath.IndexOf(':');

            if (pos >= 0)
            {
                normalizedPath = normalizedPath.Remove(0, pos + 1);
            }

            normalizedPath = normalizedPath.Trim('/');

            int uncompressedLength = data.Length;
            int compressedLength;

            byte[]            compressedData;
            CompressionMethod compressionMethod;

            if (this.enableCompression)
            {
                Deflater deflater = new Deflater(Deflater.DEFLATED);
                deflater.SetInput(data, 0, uncompressedLength);
                deflater.Finish();

                compressedData   = new byte[uncompressedLength];
                compressedLength = deflater.Deflate(compressedData, 0, uncompressedLength);
                if (deflater.IsFinished && compressedLength <= uncompressedLength)
                {
                    // Use deflate
                    compressionMethod = CompressionMethod.Deflate;
                }
                else
                {
                    // Force to store
                    compressedData    = data;
                    compressedLength  = uncompressedLength;
                    compressionMethod = CompressionMethod.Store;
                }
            }
            else
            {
                // Only store
                compressedData    = data;
                compressedLength  = uncompressedLength;
                compressionMethod = CompressionMethod.Store;
            }

            uint uncompressedSize = (uint)uncompressedLength;
            uint compressedSize   = (uint)compressedLength;
            uint crc32            = CRC32.Calculate(data);
            uint headerOffset     = (uint)this.zipFileWriter.Position;

            ZipWriteOnlyStorerEntry fileEntry = new ZipWriteOnlyStorerEntry(
                normalizedPath,
                uncompressedSize,
                compressionMethod,
                compressedSize,
                headerOffset,
                crc32,
                DateTime.Now,
                comment ?? ""
                );

            this.WriteFileHeader(this.zipFileWriter, fileEntry, false);

            this.zipFileWriter.WriteBytes(compressedData, 0, compressedLength);
            this.entries.AddLast(fileEntry);

            return(fileEntry);
        }
Пример #29
0
 public void CRC32_4EmptyArg_Zero()
 {
     Assert.AreEqual(0, CRC32.Calculate(new byte[0], new byte[0], new byte[0], new byte[0]));
 }
Пример #30
0
 static string Hash_CRC32(byte[] data)
 {
     return(string.Format("{0:X8}", CRC32.Calculate(data)));
 }