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.

216 Chapter 7 ■ Message Integrity

while True:

(data, addr) = UDPSock.recvfrom(buf)

h = hashlib.md5(data)

plaintext = decrypt(data)

msg = str(plaintext, 'utf-8')

print ("Received message: " + msg)

if msg == "exit":

break

if msg == 'newkey':

key = Fernet.generate_key()

f = Fernet(key)

print ("The key is :", str(key, 'utf-8'))

UDPSock.close()

os._exit(0)

The preceding code sample should generate a key for the session, as shown

in Figure 7.5.

Figure 7.5: server.py

The previous implementation will present you with a key. To get both the

client and server communicating with each other, you will need to copy and

paste the provided key to the client window, as shown in Figure 7.5:

# Save as client.py

# Message Sender

import os

from socket import *

from cryptography.fernet import Fernet

host = "127.0.0.1" # set to IP address of target computer

port = 8080

addr = (host, port)

UDPSock = socket(AF_INET, SOCK_DGRAM)

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

Saved successfully!

Ooh no, something went wrong!