Reputation: 11
I need to implement hmac with sha1 using haslib.sha1.
I defined a sha1 function which instantiates a sha1object for using it for the hmac function.
Goal is a correct padding of the Key and using it for HMAC Function with SHA-1. I get an Type error when i want to concat bytes with the int to bytes.
Input Signature for hmac_sha1 should be like:
key = bytes('Test Key', 'UTF-8')
data = bytes("Test Message", 'UTF-8')
Error - Message :
TypeError Traceback (most recent call last)
Cell In[13], line 8
4 digester = hmac.new(key, message, hashlib.sha1)
5 signature1 = digester.digest()
7 assert (
----> 8 hmac_sha1(b'Test Nachricht', b'Test Key')
9 == signature1
10 )
12 print(f"Die Signatur ist {signature1}")
Cell In[12], line 29, in hmac_sha1(data, key)
25 else:
26 K_exp = key + b'\x00' * (B-len(key))
---> 29 return sha1(bxor(K_exp,OPAD) + sha1(bxor(K_exp, IPAD)+ data))
TypeError: can't concat _hashlib.HASH to bytes
def sha1(data):
encoded_message = base64.b64encode(data) # Kodiere Binär-message in Base64
sha1_object = hashlib.sha1() #Init Hash object
sha1_object.update(encoded_message)
print(sha1_object.hexdigest())
return sha1_object
def hmac_sha1(data, key):
IPAD = b'\x36'*64
OPAD = b'\x5C'*64
B, L = B,L = hashlib.sha1().block_size, hashlib.sha1().digest_size
if(len(key) == B):
K_exp = key
elif len(key)> B:
K_exp = sha1(key) + b'\x00' *(B-L) #TODO Error wegen concat int and bytes
else:
K_exp = key + b'\x00' *(B-len(key))
return sha1(bxor(K_exp,OPAD) + sha1(bxor(K_exp, IPAD)+ data))
I already thought of editing the sha1 function, but i think i have to change the format for concatting.
Upvotes: 1
Views: 111
Reputation: 6327
You need to zip your data when concatting it
import base64
import hashlib
def sha1(data):
sha1_object = hashlib.sha1() # Init Hash object
sha1_object.update(data)
return sha1_object.hexdigest()
def hmac_sha1(data, key):
IPAD = b'\x36' * 64
OPAD = b'\x5C' * 64
B, L = hashlib.sha1().block_size, hashlib.sha1().digest_size
if len(key) == B:
K_exp = key
elif len(key) > B:
K_exp = sha1(key.encode()) + b'\x00' * (B - L)
else:
K_exp = key.encode() + b'\x00' * (B - len(key))
return sha1(
bytes([a ^ b for a, b in zip(K_exp, OPAD)]) + sha1(
bytes([a ^ b for a, b in zip(K_exp, IPAD)]) + data.encode()
)
)
Upvotes: 0