CRC.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* This file is part of SevenZipSharp.
  2. SevenZipSharp is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU Lesser General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. SevenZipSharp is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU Lesser General Public License for more details.
  10. You should have received a copy of the GNU Lesser General Public License
  11. along with SevenZipSharp. If not, see <http://www.gnu.org/licenses/>.
  12. */
  13. namespace SevenZip.Sdk
  14. {
  15. internal class CRC
  16. {
  17. public static readonly uint[] Table;
  18. private uint _value = 0xFFFFFFFF;
  19. static CRC()
  20. {
  21. Table = new uint[256];
  22. const uint kPoly = 0xEDB88320;
  23. for (uint i = 0; i < 256; i++)
  24. {
  25. uint r = i;
  26. for (int j = 0; j < 8; j++)
  27. if ((r & 1) != 0)
  28. r = (r >> 1) ^ kPoly;
  29. else
  30. r >>= 1;
  31. Table[i] = r;
  32. }
  33. }
  34. public void Init()
  35. {
  36. _value = 0xFFFFFFFF;
  37. }
  38. public void UpdateByte(byte b)
  39. {
  40. _value = Table[(((byte) (_value)) ^ b)] ^ (_value >> 8);
  41. }
  42. public void Update(byte[] data, uint offset, uint size)
  43. {
  44. for (uint i = 0; i < size; i++)
  45. _value = Table[(((byte) (_value)) ^ data[offset + i])] ^ (_value >> 8);
  46. }
  47. public uint GetDigest()
  48. {
  49. return _value ^ 0xFFFFFFFF;
  50. }
  51. private static uint CalculateDigest(byte[] data, uint offset, uint size)
  52. {
  53. var crc = new CRC();
  54. // crc.Init();
  55. crc.Update(data, offset, size);
  56. return crc.GetDigest();
  57. }
  58. private static bool VerifyDigest(uint digest, byte[] data, uint offset, uint size)
  59. {
  60. return (CalculateDigest(data, offset, size) == digest);
  61. }
  62. }
  63. }