64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
|
|
def crc16(data: bytearray, offset: int, length: int):
|
|
if data is None or offset < 0 or offset > len(data) - 1 and offset + length > len(data):
|
|
return 0
|
|
crc = 0xFFFF
|
|
for i in range(0, length):
|
|
crc ^= data[offset + i] << 8
|
|
for j in range(0, 8):
|
|
if (crc & 0x8000) > 0:
|
|
crc = (crc << 1) ^ 0x1021
|
|
else:
|
|
crc = crc << 1
|
|
return crc & 0xFFFF
|
|
|
|
|
|
def test_crc_sum():
|
|
# ignore: F401
|
|
from backend_output.python.bproto_base import crc16_calc_inital, calc_crc_sum
|
|
|
|
protocol_hash = bytes.fromhex("4a07789a41ef64c38a7edb78574497d4")
|
|
protocol_data = bytes.fromhex("c9850ff561ea6d27f3171e1c680a4607ea8fa5278ee96de5c8e0ade101bdeb4332d07cb2269a47c910ca2cfe95de9ceda0bb9ee05b0909dcaf68f6a605df7dd4")
|
|
|
|
inital = crc16_calc_inital(protocol_hash)
|
|
checksum = calc_crc_sum(protocol_data, inital)
|
|
ref_data = protocol_hash + protocol_data
|
|
assert crc16(ref_data, 0, len(ref_data)) == checksum
|
|
|
|
protocol_hash = bytes.fromhex("4a07789a41ef64c38a7edb78574497d4")
|
|
protocol_data = bytes.fromhex("8898ebbd28e82663b71a7bbf8bc5ec72872ca057a77e31c1c11deff5004e8985767acb75da9b2d1dea643b08ed0458477e4a")
|
|
|
|
inital = crc16_calc_inital(protocol_hash)
|
|
checksum = calc_crc_sum(protocol_data, inital)
|
|
ref_data = protocol_hash + protocol_data
|
|
assert crc16(ref_data, 0, len(ref_data)) == checksum
|
|
|
|
protocol_hash = bytes.fromhex("4a07789a41ef64c38a7edb78574497d4")
|
|
protocol_data = bytes.fromhex("ca321a923e202614482cb392d858175ffe9f117d38")
|
|
|
|
inital = crc16_calc_inital(protocol_hash)
|
|
checksum = calc_crc_sum(protocol_data, inital)
|
|
ref_data = protocol_hash + protocol_data
|
|
assert crc16(ref_data, 0, len(ref_data)) == checksum
|
|
|
|
|
|
def test_crc_sum_change():
|
|
# ignore: F401
|
|
from backend_output.python.bproto_base import crc16_calc_inital, calc_crc_sum
|
|
|
|
protocol_hash = bytes.fromhex("4a07789a41ef64c38a7edb78574497d4")
|
|
protocol_data = bytes.fromhex("ca321a923e202614482cb392d858175ffe9f117d38")
|
|
|
|
inital = crc16_calc_inital(protocol_hash)
|
|
checksum = calc_crc_sum(protocol_data + b"\xaa", inital)
|
|
ref_data = protocol_hash + protocol_data
|
|
assert crc16(ref_data, 0, len(ref_data)) != checksum
|
|
|
|
protocol_hash = bytes.fromhex("4a07789a41ef64c38a7edb78574497d4")
|
|
protocol_data = bytes.fromhex("ca321a923e202614482cb392d858175ffe9f117d38")
|
|
|
|
inital = crc16_calc_inital(protocol_hash[-1:] + b"\xaa")
|
|
checksum = calc_crc_sum(protocol_data, inital)
|
|
ref_data = protocol_hash + protocol_data
|
|
assert crc16(ref_data, 0, len(ref_data)) != checksum
|