Simple XOR Hash


/ Published in: Python
Save to your folder(s)

This is a simple hash that pads its input to the block size and XORs every block together. Output is in hexadecimal octets. Probability of collisions is extremely high and they are easy to calculate, although the function is one-way, so this is more (though, not very) useful as a checksum.


Copy this code and paste it in your HTML
  1. def xor_hash(a_value, block_size=16):
  2. value_size = len(a_value)
  3. padding = value_size % block_size
  4. padding = 0 if padding == 0 else block_size - padding
  5. value_size += padding
  6.  
  7. if (padding != 0):
  8. a_value += b'\x00' * padding
  9.  
  10. retval = bytearray(bytes(block_size))
  11.  
  12. for a_block in range(1, value_size, block_size):
  13. a_block = a_value[(a_block-1):(a_block+block_size-1)]
  14.  
  15. for i in range(0, block_size):
  16. retval[i] ^= a_block[i]
  17.  
  18. return retval
  19.  
  20. if (__name__ == "__main__"):
  21. import sys
  22.  
  23. a_value = bytearray(' '.join(sys.argv[1:]), encoding="utf-8")
  24. a_hash = xor_hash(a_value)
  25. print(''.join(["%0.2x" % a_byte for a_byte in a_hash]))

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.