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 213

# Save as server.py

# Message Receiver

import os

from socket import *

host = ""

port = 13000

buf = 1024

addr = (host, port)

UDPSock = socket(AF_INET, SOCK_DGRAM)

UDPSock.bind(addr)

print ("Waiting to receive messages...")

while True:

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

print ("Received message: " + str(data,'utf-8'))

if data == "exit":

break

UDPSock.close()

os._exit(0)

Create a Client Socket

The next Python code will create the client that will send messages to the server

over port 13000. Once the code executes, it will launch a command window

that states Enter message to send or type ‘exit’. Messages entered here will be sent

unencrypted to the server. We will explore how to encrypt and decrypt these

messages using symmetric encryption. Once you complete the following script,

you will be able to send messages from the client to the server, as shown in

Figure 7.4.

# Save as client.py

# Message Sender

import os

from socket import *

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

port = 13000

addr = (host, port)

UDPSock = socket(AF_INET, SOCK_DGRAM)

while True:

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

UDPSock.sendto(data, addr)

if data == "exit":

break

UDPSock.close()

os._exit(0)

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

Saved successfully!

Ooh no, something went wrong!