Utility.Verifier.Crc32.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //------------------------------------------------------------
  2. // Game Framework
  3. // Copyright © 2013-2021 loyalsoft. All rights reserved.
  4. // Homepage: http://www.game7000.com/
  5. // Feedback: http://www.game7000.com/
  6. //------------------------------------------------------------
  7. namespace GameFramework
  8. {
  9. public static partial class Utility
  10. {
  11. public static partial class Verifier
  12. {
  13. /// <summary>
  14. /// CRC32 算法。
  15. /// </summary>
  16. private sealed class Crc32
  17. {
  18. private const int TableLength = 256;
  19. private const uint DefaultPolynomial = 0xedb88320;
  20. private const uint DefaultSeed = 0xffffffff;
  21. private readonly uint m_Seed;
  22. private readonly uint[] m_Table;
  23. private uint m_Hash;
  24. public Crc32()
  25. : this(DefaultPolynomial, DefaultSeed)
  26. {
  27. }
  28. public Crc32(uint polynomial, uint seed)
  29. {
  30. m_Seed = seed;
  31. m_Table = InitializeTable(polynomial);
  32. m_Hash = seed;
  33. }
  34. public void Initialize()
  35. {
  36. m_Hash = m_Seed;
  37. }
  38. public void HashCore(byte[] bytes, int offset, int length)
  39. {
  40. m_Hash = CalculateHash(m_Table, m_Hash, bytes, offset, length);
  41. }
  42. public uint HashFinal()
  43. {
  44. return ~m_Hash;
  45. }
  46. private static uint CalculateHash(uint[] table, uint value, byte[] bytes, int offset, int length)
  47. {
  48. int last = offset + length;
  49. for (int i = offset; i < last; i++)
  50. {
  51. unchecked
  52. {
  53. value = (value >> 8) ^ table[bytes[i] ^ value & 0xff];
  54. }
  55. }
  56. return value;
  57. }
  58. private static uint[] InitializeTable(uint polynomial)
  59. {
  60. uint[] table = new uint[TableLength];
  61. for (int i = 0; i < TableLength; i++)
  62. {
  63. uint entry = (uint)i;
  64. for (int j = 0; j < 8; j++)
  65. {
  66. if ((entry & 1) == 1)
  67. {
  68. entry = (entry >> 1) ^ polynomial;
  69. }
  70. else
  71. {
  72. entry >>= 1;
  73. }
  74. }
  75. table[i] = entry;
  76. }
  77. return table;
  78. }
  79. }
  80. }
  81. }
  82. }