07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

202 Chapter 7 ■ Message Integrity

It is important to note that hash functions that are not collision resistant can

be vulnerable to the birthday attack; you learn more about this attack shortly.

First, you will explore the HMAC function and learn how to incorporate the

same logic into a standard hash library. Open the Python interpreter and enter

the first two lines of code to verify that you are getting the same tag:

import hmac, hashlib

print(hmac.new(b"secretkey", b"our secret message", hashlib.sha256).

hexdigest())

78c736db86abd16023a23355f4ad3005e77dec6d8c960d06ea3c4a9aba9c449f

SHA256 has a 64-byte block length; to build an HMAC by hand, you need to

build K + , ipad, and opad:

import binascii, hashlib

k = b"secretkey"

msg = b"our secret message"

kplus = k + b"\x00"*(64-len(k))

ipad = b"\x36"*64

opad = b"\x5C"*64

def XOR(raw1, raw2):

return binascii.unhexlify(format(int(binascii.hexlify(raw1), 16) ^

int(binascii.hexlify(raw2), 16), 'x'))

tag = hashlib.sha256(XOR(kplus, opad) + hashlib.sha256(XOR(kplus, ipad)

+ msg).digest()).digest()

print(binascii.hexlify(tag))

Confirm that this manual computation matches the library implementation.

In our next script, we will apply an HMAC digest to a signed message.

Using HMAC to Sign Message

The file that we are creating the message digest for is a simple text file that contains

only Hello. When run, the code reads a data file and computes an HMAC

signature for it:

import hmac

myKey = b'this_is_my_secret'

digest_maker = hmac.new(myKey)

with open('test.txt', 'rb') as f:

while True:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!