Search code examples
pythoncryptographyhmacdigest

Hmac in message vs HMac in digest


I am currently learning the basic of cryptography when i come across this piece of Python code

if self.shared_hash != None:
            h = HMAC.new(self.shared_hash)
            hmac = data[:h.digest_size*2] #Get the HMAC part of the message
            data = data[h.digest_size*2:] # Get the data part of the message
            h.update(data)
            if h.hexdigest() != str(hmac, 'ascii'): #HMAC is not right, so raise an error
                if self.verbose:
                    print("Bad message")
                    print("HMAC from message:",str(hmac,'ascii'))
                    print("HMAC from digest:",h.hexdigest())
                    print("Not verifying message:",data)
raise RuntimeError("Bad message: HMAC does not match")

Since HMAC is to check the authenticity of a message, i understand its important to check the HMAC. But why are we comparing the HMAC from the message and the HMAC from the digest. Moreover, what is the HMAC from the digest? Is it just a hash of a message?


Solution

  • Since HMAC is to check the authenticity of a message, i understand its important to check the HMAC

    So how do you verify that the message is authentic ?

    When you recieve an HMAC message it contains two parts. The actual message and the HMAC tag. Now to verify that the message is authentic , you need to construct an HMAC tag with the message recieved and the secret MAC key you have using the HMAC algorithm. Then you compare the generated HMAC with the HMAC that came along with message to see if they match.

    But why are we comparing the HMAC from the message and the HMAC from the digest.

    To verify that the message is authentic just as explained above.

    Moreover, what is the HMAC from the digest?

    The HMAC that you generated to compare against the HMAC that came along with message.