Guest User

Untitled

a guest
Mar 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. # Calculate and verify checksums of hexadecimal values
  2.  
  3. import sys
  4.  
  5. def checksum(inputMessage, operation):
  6. """Take in a hex value, and an operation to perform. If the
  7. operation is 'c', create a checksum and return that inputMessage with
  8. the checksum appended. If the operation is 'v', validate the checksum.
  9. Return 0 if it's invalid, and 1 if it's valid.
  10. """
  11. sum = 0
  12. digits = [int(i,16) for i in inputMessage]
  13.  
  14. for i in range(0, len(digits)):
  15. sum = (sum + digits[i]) % 16
  16.  
  17. if operation == 'c':
  18. sum = (sum ^ 15) + 1
  19. return inputMessage + str(sum)
  20.  
  21. if operation == 'v':
  22. if sum == 0:
  23. return 1
  24. else:
  25. return 0
  26.  
  27.  
  28. def main():
  29. """Pass the hex value to the program as a commandline argument.
  30. Example: python3 checksum.py BF1942
  31. """
  32.  
  33. hexValue = sys.argv[1]
  34. messageWithChecksum = checksum(hexValue, 'c')
  35.  
  36. print("Generate checksum")
  37. print("Message with checksum appended: " + messageWithChecksum)
  38. print("Validate checksum: " +
  39. "Valid" if checksum(messageWithChecksum, 'v') else "Failed")
  40.  
  41.  
  42. if __name__ == '__main__':
  43. main()
Add Comment
Please, Sign In to add comment