From 0acfff00771d0f944db0c91ebd366e0cb3d01591 Mon Sep 17 00:00:00 2001 From: Alexey 'Cluster' Avdyukhin Date: Tue, 8 Nov 2022 10:53:44 +0400 Subject: Padding fix, checksum fix --- Crc32.cs | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Crc32.cs (limited to 'Crc32.cs') diff --git a/Crc32.cs b/Crc32.cs new file mode 100644 index 0000000..33acf83 --- /dev/null +++ b/Crc32.cs @@ -0,0 +1,65 @@ +using System; +using System.Security.Cryptography; + +namespace com.clusterrr.Famicom.Containers +{ + /// + /// CRC32 calculator + /// + internal class Crc32 : HashAlgorithm + { + private readonly uint[] table = new uint[256]; + private uint crc = 0xFFFFFFFF; + + public Crc32() + { + // Calculate table + uint poly = 0xedb88320; + uint temp; + for (uint i = 0; i < table.Length; ++i) + { + temp = i; + for (int j = 8; j > 0; --j) + { + if ((temp & 1) == 1) + { + temp = (uint)((temp >> 1) ^ poly); + } + else + { + temp >>= 1; + } + } + table[i] = temp; + } + } + + public override void Initialize() + { + } + + public override bool CanReuseTransform => false; + + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + while (cbSize > 0) + { + var pos = ibStart; + byte index = (byte)(((crc) & 0xff) ^ array[pos]); + crc = (crc >> 8) ^ table[index]; + ibStart++; + cbSize--; + } + } + + protected override byte[] HashFinal() + { + return BitConverter.GetBytes(~crc); + } + + public override bool CanTransformMultipleBlocks => true; + public override byte[] Hash => BitConverter.GetBytes(~crc); + public override int HashSize => 32; + + } +} -- cgit v1.2.3