]> git.zerfleddert.de Git - proxmark3-svn/blame_incremental - common/crc.c
fix 'lf pcf7931 bruteforce' (bug reported in http://www.proxmark.org/forum/viewtopic...
[proxmark3-svn] / common / crc.c
... / ...
CommitLineData
1//-----------------------------------------------------------------------------
2// This code is licensed to you under the terms of the GNU GPL, version 2 or,
3// at your option, any later version. See the LICENSE.txt file for the text of
4// the license.
5//-----------------------------------------------------------------------------
6// Generic CRC calculation code.
7//-----------------------------------------------------------------------------
8#include "crc.h"
9#include <stdint.h>
10#include <stddef.h>
11
12#define BITMASK(X) (1 << (X))
13
14uint32_t reflect(uint32_t v, int b) {
15 uint32_t t = v;
16 for (int i = 0; i < b; ++i) {
17 if (t & 1)
18 v |= BITMASK((b - 1) - i);
19 else
20 v &= ~BITMASK((b - 1) - i);
21 t >>= 1;
22 }
23 return v;
24}
25
26void crc_init(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor)
27{
28 crc->order = order;
29 crc->polynom = polynom;
30 crc->initial_value = initial_value;
31 crc->final_xor = final_xor;
32 crc->mask = (1L<<order)-1;
33 crc_clear(crc);
34}
35
36void crc_update(crc_t *crc, uint32_t data, int data_width)
37{
38 int i;
39 for(i=0; i<data_width; i++) {
40 int oldstate = crc->state;
41 crc->state = crc->state >> 1;
42 if( (oldstate^data) & 1 ) {
43 crc->state ^= crc->polynom;
44 }
45 data >>= 1;
46 }
47}
48
49void crc_clear(crc_t *crc)
50{
51 crc->state = crc->initial_value & crc->mask;
52}
53
54uint32_t crc_finish(crc_t *crc)
55{
56 return ( crc->state ^ crc->final_xor ) & crc->mask;
57}
58
59//credits to iceman
60uint32_t CRC8Maxim(uint8_t *buff, size_t size)
61{
62 crc_t crc;
63 crc_init(&crc, 9, 0x8c, 0x00, 0x00);
64 crc_clear(&crc);
65
66 for (size_t i=0; i < size; ++i){
67 crc_update(&crc, buff[i], 8);
68 }
69 return crc_finish(&crc);
70}
71
72// width=8 poly=0x1d, init=0xc7 (0xe3 - WRONG! but it mentioned in MAD datasheet) refin=false refout=false xorout=0x00 name="CRC-8/MIFARE-MAD"
73uint32_t CRC8Mad(uint8_t *buff, size_t size) {
74 crc_t crc;
75 crc_init(&crc, 8, reflect(0x1d, 8), reflect(0xc7, 8), 0);
76 for (int i = 0; i < size; ++i)
77 crc_update(&crc, reflect(buff[i], 8), 8);
78
79 return reflect(crc_finish(&crc), 8);
80}
Impressum, Datenschutz