| 1 | #include <stdint.h> |
| 2 | #include <stddef.h> |
| 3 | #include "crc32.h" |
| 4 | |
| 5 | #define htole32(x) (x) |
| 6 | #define CRC32_PRESET 0xFFFFFFFF |
| 7 | |
| 8 | |
| 9 | static void crc32_byte (uint32_t *crc, const uint8_t value); |
| 10 | |
| 11 | static void crc32_byte (uint32_t *crc, const uint8_t value) { |
| 12 | /* x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1 */ |
| 13 | const uint32_t poly = 0xEDB88320; |
| 14 | |
| 15 | *crc ^= value; |
| 16 | for (int current_bit = 7; current_bit >= 0; current_bit--) { |
| 17 | int bit_out = (*crc) & 0x00000001; |
| 18 | *crc >>= 1; |
| 19 | if (bit_out) |
| 20 | *crc ^= poly; |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | void crc32 (const uint8_t *data, const size_t len, uint8_t *crc) { |
| 25 | uint32_t desfire_crc = CRC32_PRESET; |
| 26 | for (size_t i = 0; i < len; i++) { |
| 27 | crc32_byte (&desfire_crc, data[i]); |
| 28 | } |
| 29 | |
| 30 | *((uint32_t *)(crc)) = htole32 (desfire_crc); |
| 31 | } |
| 32 | |
| 33 | void crc32_append (uint8_t *data, const size_t len) { |
| 34 | crc32 (data, len, data + len); |
| 35 | } |