IamRichter
IamRichter

Reputation: 15

Calculate the checksum using xor in python 3

So, i am collecting some codes from a ip device, and i am struggling to calc it's checksum. For example, this is the package that I collected using a simple socket in python:

b'\x07\x94ES(\xff\xceY:'

Converting it to a more human readable using .hex(), i got this:

0794455328ffce593a

3a is the given checksum, i should be able to get the same value by xor the code (like 07^94^45^53^28^ff^ce^59^FF = 3a), but i can't figure out how. I tried to xor the values as integers, but the result was way off. BTW, 07 is the number of bytes of the package.

Another string example is

b'\x11\xb0\x11\x05\x03\x02\x08\x01\x08\x01\x03\x08\x03\n\x01\n\n\x01I'

Anyone have an idea?

Upvotes: 0

Views: 2810

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

with a little guess work and 2 examples, it seems that the xor algorithm used is flipping all the bits somewhere. Doing that flip makes the value of the examples match.

data_list = [b'\x07\x94ES(\xff\xceY:', b'\x11\xb0\x11\x05\x03\x02\x08\x01\x08\x01\x03\x08\x03\n\x01\n\n\x01I']
for data in data_list:
    value = data[0]
    for d in data[1:-1]:
        value ^= d

    checksum = value ^ 0xFF  # negate all the bits

    if checksum == data[-1]:
        print("checksum match for {}".format(data))
    else:
        print("checksum DOES NOT MATCH for {}".format(data))

prints:

checksum match for b'\x07\x94ES(\xff\xceY:'
checksum match for b'\x11\xb0\x11\x05\x03\x02\x08\x01\x08\x01\x03\x08\x03\n\x01\n\n\x01I'

not sure if it helps future readers but at least this is solved.

Upvotes: 3

GordonAitchJay
GordonAitchJay

Reputation: 4860

If you're curious, here's a direct port of the C# implementation you put in a comment:

def calculate(data):
    xor = 0
    for byte in data:
        xor ^= byte

    xor ^= 0xff
    return xor

I didn't realise the last byte was in fact the checksum.

Upvotes: 0

Related Questions