Posted By

weilawei on 05/09/12


Tagged

code message hash authentication hmac hashed


Versions (?)

HMAC


 / Published in: Python
 

HMAC, pass a hash from Crypto.Hash in PyCrypto. Key should be a bytes object. Returns a bytearray.

  1. def pad_key(a_hash, a_key):
  2. block_size = a_hash.digest_size
  3.  
  4. if (len(a_key) > block_size):
  5. a_hasher = a_hash.new()
  6. a_hash.update(a_key)
  7. return a_hasher.digest()
  8. elif (len(a_key) < block_size):
  9. return a_key + (b'\x00' * (block_size - len(a_key)))
  10.  
  11. return a_key
  12.  
  13. def HMAC(a_hash, a_key, data):
  14. block_size = a_hash.digest_size
  15. a_key = pad_key(a_hash, a_key)
  16. block_range = bytearray([i for i in range(block_size)])
  17. xor_5c = bytearray.maketrans(block_range, bytearray([i ^ 0x5c for i in range(block_size)]))
  18. xor_36 = bytearray.maketrans(block_range, bytearray([i ^ 0x36 for i in range(block_size)]))
  19.  
  20. inner_hasher = a_hash.new()
  21. outer_hasher = inner_hasher.copy()
  22. final_hasher = inner_hasher.copy()
  23.  
  24. inner_hasher.update(a_key.translate(xor_36) + data)
  25. outer_hasher.update(a_key.translate(xor_5c) + inner_hasher.digest())
  26. final_hasher.update(outer_hasher.digest())
  27.  
  28. return bytearray(final_hasher.digest())

Report this snippet  

You need to login to post a comment.