Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Calculate and verify checksums of hexadecimal values
- import sys
- def checksum(inputMessage, operation):
- """Take in a hex value, and an operation to perform. If the
- operation is 'c', create a checksum and return that inputMessage with
- the checksum appended. If the operation is 'v', validate the checksum.
- Return 0 if it's invalid, and 1 if it's valid.
- """
- sum = 0
- digits = [int(i,16) for i in inputMessage]
- for i in range(0, len(digits)):
- sum = (sum + digits[i]) % 16
- if operation == 'c':
- sum = (sum ^ 15) + 1
- return inputMessage + str(sum)
- if operation == 'v':
- if sum == 0:
- return 1
- else:
- return 0
- def main():
- """Pass the hex value to the program as a commandline argument.
- Example: python3 checksum.py BF1942
- """
- hexValue = sys.argv[1]
- messageWithChecksum = checksum(hexValue, 'c')
- print("Generate checksum")
- print("Message with checksum appended: " + messageWithChecksum)
- print("Validate checksum: " +
- "Valid" if checksum(messageWithChecksum, 'v') else "Failed")
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment