crc8_unittest.cc 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. //
  5. // Uniitest for data encryption functions.
  6. #include <stddef.h>
  7. #include "testing/gmock/include/gmock/gmock.h"
  8. #include "testing/gtest/include/gtest/gtest.h"
  9. #include "rlz/lib/crc8.h"
  10. TEST(Crc8Unittest, TestCrc8) {
  11. struct Data {
  12. char string[10];
  13. // Externally calculated checksums use
  14. // http://www.zorc.breitbandkatze.de/crc.html
  15. // with the ATM HEC paramters:
  16. // CRC-8, Polynomial 0x07, Initial value 0x00, Final XOR value 0x55
  17. // (direct, don't reverse data byes, don't reverse CRC before final XOR)
  18. unsigned char external_crc;
  19. int random_byte;
  20. unsigned char corrupt_value;
  21. } data[] = {
  22. {"Google", 0x01, 2, 0x53},
  23. {"GOOGLE", 0xA6, 4, 0x11},
  24. {"My CRC 8!", 0xDC, 0, 0x50},
  25. };
  26. unsigned char* bytes;
  27. unsigned char crc;
  28. bool matches;
  29. int length;
  30. for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); ++i) {
  31. bytes = reinterpret_cast<unsigned char*>(data[i].string);
  32. crc = 0;
  33. matches = false;
  34. length = strlen(data[i].string);
  35. // Calculate CRC and compare against external value.
  36. rlz_lib::Crc8::Generate(bytes, length, &crc);
  37. EXPECT_TRUE(crc == data[i].external_crc);
  38. rlz_lib::Crc8::Verify(bytes, length, crc, &matches);
  39. EXPECT_TRUE(matches);
  40. // Corrupt string and see if CRC still matches.
  41. data[i].string[data[i].random_byte] = data[i].corrupt_value;
  42. rlz_lib::Crc8::Verify(bytes, length, crc, &matches);
  43. EXPECT_FALSE(matches);
  44. }
  45. }