Skip to content

Instantly share code, notes, and snippets.

@robinkrens
Created February 23, 2024 00:37
Show Gist options
  • Save robinkrens/b0783d9d0de5199804d81db1e30e051d to your computer and use it in GitHub Desktop.
Save robinkrens/b0783d9d0de5199804d81db1e30e051d to your computer and use it in GitHub Desktop.
beken bk3231 16-bit CRC add
# by mr_woggle - 2024 (c)
# free for all :D
import os
POLY = 0x8005
START_VAL = 0xFFFF
IN_FILE = "test.bin"
OUT_FILE = "test_encrypted.bin"
def crc16(data, poly, init_value=0):
crc = init_value
for byte in data:
crc ^= byte << 8
for _ in range(8):
if crc & 0x8000:
crc = (crc << 1) ^ poly
else:
crc <<= 1
return crc & 0xFFFF
test_message = bytearray(b'\x00' * 3 + b'\x02' + b'\x00' * 28) # test message, ignore
def add_crc16(input_file, output_file):
val = START_VAL
with open(input_file, 'rb') as infile, open(output_file, 'wb') as outfile:
chunk_size = 32
while True:
chunk = infile.read(chunk_size)
if not chunk:
break
if len(chunk) < chunk_size:
chunk += b'\xFF' * (chunk_size - len(chunk))
chunk = chunk[:-1] + b'\xFF' # last byte also 0xFF?
outfile.write(chunk)
out = crc16(chunk, POLY, val)
crc_bytes = out.to_bytes(length=2, byteorder='big')
outfile.write(crc_bytes) # Add two bytes (16-bit crc)
add_crc16(IN_FILE, OUT_FILE)
print("size after adding crc: ", hex(os.path.getsize(OUT_FILE)))
#crc = crc16(message, POLY, START_VAL)
#print("crc value:", hex(crc))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment