hex_checksum.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. import sys
  3. """
  4. PSA Checksum Calculator
  5. This script calculates the 2-byte checksum used in PSA multicast protocol messages.
  6. The checksum algorithm is based on reverse-engineered firmware behavior.
  7. How it works:
  8. -------------
  9. - Initialize a 16-bit value `var_e` to 0x0000
  10. - For each byte in the payload:
  11. - Add the byte's index to its value (i.e., byte + index)
  12. - XOR the result into `var_e`
  13. - The result is a 2-byte checksum (big endian: high byte first, low byte second)
  14. This checksum is appended to the payload to form a valid message.
  15. """
  16. def compute_psa_checksum(data: bytes) -> bytes:
  17. var_e = 0x0000
  18. for i in range(len(data)):
  19. var_e ^= (data[i] + i) & 0xFFFF
  20. return var_e.to_bytes(2, 'big')
  21. def add_checksum(hexstring: str) -> str:
  22. try:
  23. data = bytes.fromhex(hexstring.strip())
  24. except ValueError:
  25. return "Invalid hex input!"
  26. checksum = compute_psa_checksum(data)
  27. return (data + checksum).hex()
  28. if __name__ == "__main__":
  29. if len(sys.argv) != 2:
  30. print("Usage: ./hex_checksum.py <hexstring_without_checksum>")
  31. sys.exit(1)
  32. result = add_checksum(sys.argv[1])
  33. print(result)