What is the difference between my HMAC-512 and Python's official HMAC-512?

65 Views Asked by At

This is the python code I have been asked to do for my Cryptography assignment, that is to implement the official HMAC function from RFC2104

from hashlib import sha512
b = 512 #block size of SHA-512

def HMAC(key, message, h, b) :
    #This function proceeds to do the 7 Hmac steps as defined in RFC 2104
    #opad and ipad initialization
    B = b//8 #The number of bytes of h output
    ipad = 0x36
    opad = 0x5c

    #Step 1 : we manage to set the key to B bytes
    if len(key) > b :
        k = bytearray((h(k).digest())) #By hashing it if it's too long
    else :
        k = key + bytearray(B - len(key)) #Or by padding the right of k with zeros
    print(k, len(k))

    #We compute kXORopad and kXORipad by doing byte by byte XOR
    kXopad = bytearray(B) #Bytearray of size B
    kXipad = bytearray(B)
    for i in range(B) :
        kXipad[i] ^= ipad;
        kXopad[i] ^= opad;
    
    sub_result = h() #Here we are doing the right side of the equation
    sub_result.update(kXipad)
    sub_result.update(message)
    print(kXipad, len(kXipad))
    print(sub_result.digest())

    sub_result = bytearray(sub_result.digest())

    result = h()
    result.update(kXopad)
    print(kXopad, len(kXopad))
    print(result.digest())
    result.update(sub_result)

    #We will return an int
    return result.hexdigest()

#We deal with bytes 
message = "a"#This input string is being used to test my own implementation of HMAC-SHA-512."
key = "a"
my_Hmac = HMAC(key.encode(), message.encode(), sha512, b)
print(my_Hmac)

import hmac
official_hmac = hmac.new(key.encode(), message.encode(), digestmod = sha512)
print(official_hmac.name)
print(official_hmac.hexdigest())
print(my_Hmac == official_hmac.hexdigest())

This is the output of my hmac hexdigest() : 4f330db94c708a6c6b54b009e48c54a1fa1e2fad77728c2d6c28fcdb7f702fa572ea928da2154537b7cef8f4f0389cfa9c7b67ebad21b445e58c228ead9e8c15

This is the output of Python's hmac hexdigest() : b37ee7821bf96e293def120539070a3010f69c37a247bb4bc1344d3491b89844525519df30d89a49d2537905b30cfa7f3a6ee54324eb1c280af5a747f3baaac5

Also, I found a website calculating HMAC, and this is the output from https://www.freeformatter.com/hmac-generator.html#before-output with sha512 : fc8c80e6b943cd07eccecf01bc6038bae68ebb6fa2e1e62b44753d7c177af7a46b089df349a19f7622a22312c76906ca9c984e1446d3ab86a98fdfa1425341c5

Python's "hmac" library (https://docs.python.org/3/library/hmac.html) says its HMAC is as it is defined in RFC2104 (https://datatracker.ietf.org/doc/html/rfc2104.html). I looked that up and tried to do every step of the algorithm one by one : H(K XOR opad, H(K XOR ipad, text)) Could anyone tell me what I did wrong that differs from the official version of HMAC? Maybe I failed importing hmac? Maybe both Thank you very much

0

There are 0 best solutions below