From 8367c8bbc1168a5005082e4d42f81adeeb49a648 Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Fri, 8 Nov 2019 14:46:23 -0500 Subject: [PATCH] Properly handle parity bits in codeToHex --- doorUtil.py | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/doorUtil.py b/doorUtil.py index 663fef3..67d9b0f 100644 --- a/doorUtil.py +++ b/doorUtil.py @@ -1,21 +1,35 @@ #!/usr/bin/env python3 +import bitstring + import requests import csv from io import StringIO from common import * -def hexToCode(hex): - b = bin(int(hex, 16))[2:] - facility = int(b[0:8], 2) - code = int(b[9:24], 2) - return((facility, code)) +# Reference for H10301 card format: +# https://www.hidglobal.com/sites/default/files/hid-understanding_card_data_formats-wp-en.pdf + + +def hexToCode(h): + b = bitstring.Bits(hex=h) + facility = b[7:15].uint + code = b[15:31].uint + return ((facility, code)) + def codeToHex(facility, code): - return "{:08X}".format(int(bin(facility)[2:] + "0" + bin(code)[2:] + "1", 2)) + b = bitstring.pack('0b000000, uint:1, uint:8, uint:16, uint:1', 0, + facility, code, 0) + # calculate parity bits + b[6] = b[7:19].count(1) % 2 # even parity + b[31] = not (b[19:31].count(1) % 2) # odd parity + return b.hex.upper() + # hexToCode("01E29DA1") <-> codeToHex(241, 20176) + def forEachDoor(fxn): for door in doors.values(): print(door.name)