0

I'm trying to implement my own HMAC-SHA1 function in python but It seems to always give me the wrong checksum at the end which I Can't see why

""" An Hmac Implementation of SHA-1 """
from Crypto.Hash import SHA1

hasher = SHA1.new()

password = b"test"
message = b"NAME"

pad_length = 64 - len(password)
key = bytes(pad_length) + password

ipad_num = "01011100" * 64
opad_num = "00110110" * 64

ipad = int.from_bytes(key, byteorder="big") ^ int(ipad_num, base=2)
opad = int.from_bytes(key, byteorder="big") ^ int(opad_num, base=2)

ipad = int.to_bytes(ipad, length=64, byteorder="big")
opad = int.to_bytes(opad, length=64, byteorder="big")

hasher.update(ipad + message)
inner_hash = hasher.digest()
print("inner hash {}".format(inner_hash.hex()))

hasher = SHA1.new()
hasher.update(opad + inner_hash)
print("final hash {}".format(hasher.hexdigest()))

which is supposed to give me this checksum: for message = NAME password = test

3e0f1cc6c2d787afe49345986212f60d3d4d300d

but instead it give me this checksum

7d6b1ba137a44ee9e083d8e3ba5a84fd739751f4
KMG
  • 1,433
  • 1
  • 8
  • 19
  • Why aren't you using the built-in `hashlib` and `hmac` libraries? Also, does [this](https://stackoverflow.com/questions/8338661/implementation-hmac-sha1-in-python) help? – Random Davis Jan 05 '21 at 21:38
  • @RandomDavis thanks a lot but I'm trying to implement it myself as a practice this link is using the built in one. – KMG Jan 05 '21 at 21:42

1 Answers1

2

I would recommend using hmac library python provides unless you are learning cryptography.

Here's the fixed code:

""" An Hmac Implementation of SHA-1 """
from Crypto.Hash import SHA1

hasher = SHA1.new()

password = b"test"
message = b"NAME"

pad_length = 64 - len(password) # TODO: support longer key
key = password + bytes(pad_length) # padding should be on the right

ipad_num = "00110110" * 64 # ipad should be 0x36
opad_num = "01011100" * 64 # opad should be 0x5c

ipad = int.from_bytes(key, byteorder="big") ^ int(ipad_num, base=2)
opad = int.from_bytes(key, byteorder="big") ^ int(opad_num, base=2)

ipad = int.to_bytes(ipad, length=64, byteorder="big")
opad = int.to_bytes(opad, length=64, byteorder="big")

hasher.update(ipad + message)
inner_hash = hasher.digest()
print("inner hash {}".format(inner_hash.hex()))

hasher = SHA1.new()
hasher.update(opad + inner_hash)
print("final hash {}".format(hasher.hexdigest()))
Coxxs
  • 460
  • 4
  • 9