07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7 ■ Message Integrity 221

f = Fernet(key)

def encrypt(plaintext):

h = hashlib.md5(plaintext).hexdigest()

print("Message hash: " + h)

mmac = str(str(plaintext,'utf-8') + h).encode()

msg = f.encrypt(mmac)

return msg

while True:

data = str(input("Enter message to send or type 'exit': ")).encode()

ciphertext = encrypt(data)

UDPSock.sendto(ciphertext, addr)

if data == b'exit':

break

if data == b'newkey':

key = input("Enter the secret key: ")

f = Fernet(key)

UDPSock.close()

os._exit(0)

The preceding code sample will generate the message digest and send it to

the server so that the server can determine if the received message has been

tampered with. Your result should appear similar to Figure 7.9.

Figure 7.9: Message and MAC client

Summary

In this chapter, we continued our exploration of hashing algorithms using

Python. Hopefully, you understand how to effectively use message digests to

protect the integrity of your messages. Algorithms such as SHA1 and MD5 have

proven to be victims of birthday attacks and the length extension attack. One

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

Saved successfully!

Ooh no, something went wrong!