Skip to content

Instantly share code, notes, and snippets.

@andreasWallner
Created August 24, 2021 23:59
Show Gist options
  • Save andreasWallner/06db7bd45f67d674f379fe3b8d030fb6 to your computer and use it in GitHub Desktop.
Save andreasWallner/06db7bd45f67d674f379fe3b8d030fb6 to your computer and use it in GitHub Desktop.
Simple CRC toy examples to try to figure out parameters of the one used in ISO 14443
def str2int(s):
i = 0
for c in s:
i = (i << 1) + (1 if c == '1' else 0)
return i
def xor(a, b):
return ['1' if aa != bb else '0' for aa, bb in zip(a, b)]
def inv(a):
return ['1' if aa == '0' else '0' for aa in a]
def space(s, length=8):
pieces = [s[0+i:length+i] for i in range(0, len(s), length)]
return ' '.join(pieces)
def divide(data, poly):
poly = poly.lstrip('0')
shift = 0
data = list(data)
print(space(''.join(data)))
while(len(data) > (len(poly) - 1)):
print(f' {shift:2d} {str2int(data[:len(poly) - 1]):04x} {str2int(reversed(data[:len(poly) - 1])):04x}')
if data[0] == '1':
print(space(shift * '0' + ''.join(data)) + f' {str2int(data[:len(poly) - 1]):02x}')
print(space(shift * ' ' + poly))
print(space(shift * ' ' + len(poly) * '-'))
for i in range(len(poly)):
data[i] = '0' if data[i] == poly[i] else '1'
print(space((shift + 1) * ' ' + ''.join(data[1:len(poly)])))
data = data[1:]
shift += 1
normal = data
inverse = inv(data)
reverse = reversed(data)
revinv = inv(reversed(data))
mask = str2int((len(poly) - 1) * "1")
print(shift * ' ' + ''.join(data[:len(poly)]) + f' {str2int(normal):02x} i:{str2int(inverse) & mask:02x} r:{str2int(reverse):02x} ri:{str2int(revinv) & mask:02x}')
return data
def spec(data):
crc = 0xffff
for b in data:
b = (int(b) ^ crc) & 0xff
b = (b ^ (b << 4)) & 0xff
crc = (crc >> 8) ^ ((b << 8) & 0xffff) ^ ((b << 3) & 0xffff) ^ ((b >> 4) & 0xffff)
print(f'{crc:04x} {bin(crc)}')
crc = ~crc & 0xffff
print(f'{crc:04x}')
divide(16 * '1' + 8 * '0' + 16 * '0', '10001000000100001')
spec(bytes.fromhex('000000'))
print()
spec(bytes.fromhex('0faaff'))
print()
spec(bytes.fromhex('0a123456'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment