]> git.zerfleddert.de Git - proxmark3-svn/blame - common/crc.c
FIX: legic_prng.c according to user on forum ref: http://www.proxmark.org/forum...
[proxmark3-svn] / common / crc.c
CommitLineData
bd20f8f4 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//-----------------------------------------------------------------------------
68d9d60a 8#include "crc.h"
ee4e2816 9#include "util.h"
10#include <stdio.h>
73d04bb4 11#include <stdint.h>
12#include <stddef.h>
68d9d60a 13
14void crc_init(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor)
15{
16 crc->order = order;
17 crc->polynom = polynom;
18 crc->initial_value = initial_value;
19 crc->final_xor = final_xor;
20 crc->mask = (1L<<order)-1;
21 crc_clear(crc);
22}
23
24void crc_update(crc_t *crc, uint32_t data, int data_width)
25{
ee4e2816 26 for( int i=0; i < data_width; i++) {
68d9d60a 27 int oldstate = crc->state;
28 crc->state = crc->state >> 1;
29 if( (oldstate^data) & 1 ) {
30 crc->state ^= crc->polynom;
31 }
32 data >>= 1;
33 }
34}
35
36void crc_clear(crc_t *crc)
37{
38 crc->state = crc->initial_value & crc->mask;
39}
40
41uint32_t crc_finish(crc_t *crc)
42{
43 return ( crc->state ^ crc->final_xor ) & crc->mask;
44}
73d04bb4 45
e74fc2ec 46//credits to iceman
47uint32_t CRC8Maxim(uint8_t *buff, size_t size)
73d04bb4 48{
49 crc_t crc;
50 crc_init(&crc, 9, 0x8c, 0x00, 0x00);
51 crc_clear(&crc);
52
ee4e2816 53 for (size_t i=0; i < size; ++i)
73d04bb4 54 crc_update(&crc, buff[i], 8);
ee4e2816 55
73d04bb4 56 return crc_finish(&crc);
57}
ee4e2816 58
59uint32_t CRC8Legic(uint8_t *buff, size_t size) {
60
61 // Poly 0x63, reversed poly 0xC6, Init 0x55, Final 0x00
62 crc_t crc;
63 crc_init(&crc, 8, 0xC6, 0x55, 0);
64 crc_clear(&crc);
65
66 for ( int i = 0; i < size; ++i)
67 crc_update(&crc, buff[i], 8);
68 return SwapBits(crc_finish(&crc), 8);
69}
70
71uint32_t SwapBits(uint32_t value, int nrbits) {
72 uint32_t newvalue = 0;
73 for(int i = 0; i < nrbits; i++) {
74 newvalue ^= ((value >> i) & 1) << (nrbits - 1 - i);
75 }
76 return newvalue;
77}
Impressum, Datenschutz