Afghan qn

mail@pastecode.io avatar
unknown
plain_text
2 years ago
6.9 kB
3
Indexable
Never
# Task 9
def generateKey(p,m):
    if len(p) < len(m):
        diff = len(m)-len(p)
        for i in range(diff):
            p = p+p[i]
        
    return p
    
generateKey('cat','hello')

# Task 10
def encrypt(p,m):
            
    p = generateKey(p,m)
    
    pList = []
    mList = []
    
    for i in range(len(m)):
        pList.append(ord(p[i]))
        mList.append(ord(m[i]))
    
    addedList = []
    for i in range(len(mList)):
        addedList.append(mList[i] + pList[i])
    
    encryptedMessage = ''
    for i in addedList:
        encryptedMessage += chr(i)
        
    return encryptedMessage
    
    
print(encrypt('cat','hello'))

def decrypt(p,m):
    p = generateKey(p,m)
    
    pList = []
    mList = []
    
    for i in range(len(m)):
        pList.append(ord(p[i]))
        mList.append(ord(m[i]))
        
    subtractedList = []
    for i in range(len(mList)):
        subtractedList.append(mList[i]-pList[i])
        
    decryptedMessage = ''
    for i in subtractedList:
        decryptedMessage += chr(i)
        
    return decryptedMessage

print(decrypt("cat", encrypt("cat","hello")))

# Task 11
class Queue:
    def __init__(self,size):
        self.size = size
        self.head = 0
        self.tail = 0
        self.array = [None]*size
    
    def enqueue(self,obj):
        if self.tail <= len(self.array)-1:
            self.array[self.tail] = obj
            self.tail += 1
        else:
            print("Queue is full!")
        
    def dequeue(self):
        ret = self.array[0]
        if self.tail != 0:
            for i in range(1,len(self.array)):
                self.array[i-1] = self.array[i]
            self.array[-1] = None
            self.tail -= 1
            return ret
        else:
            print("Queue is empty!")

    def current_size(self):
        size = 0
        for i in self.array:
            if i != None:
                size += 1
        return size
    
    def display(self):
        ret = [str(i) for i in self.array]
        print(' '.join(ret))

# Task 12
q = Queue(266)
password = input("Set a password: ")

## Server
from socket import socket

s = socket()

port = 12345
s.bind(('localhost', port))

print("Next Action?")
print("Menu:")
print("1) Wait for connection from client for next pickup request")
print("2) Dequeue")
menu_option = input("Type an option: ")

if menu_option == '1':
    # Connecting to client and receiving data
    s.listen(3)
    print('Awaiting connection from pickup client...')
    
    while True:
        c, addr = s.accept()
        print('Connection established!')
        
        print('Receiving data from client...')
        data = c.recv(4096)
        data = data.decode()
        
        print("Checking client's secret key...")
        
        try:
            # client's data = "[password, team name, group's size]"
            data = decrypt(password, data)
            temp = data
            data = eval(data)
            if generateKey(data[0],temp) == generateKey(password,temp):
                print("Client's secret key is correct!")

                print(f"Client's Team name: {data[1]}")
                print(f"Group size: {data[2]}")
                print(f"Number of passengers in queue: {q.current_size()}")
                
                if (266-q.current_size()) >= data[2]:
                    print("You have capacity for them.")
                    confirm = input("Confirm pickup (Y/N): ")
                    if confirm == 'Y':
                        for i in range(data[2]):
                            q.enqueue(data[1])
                        print("Added to queue. Items in queue now are:")
                        q.display()
                        server_data = "Accepted"
                        server_data = encrypt(password, server_data)
                        c.send(server_data.encode())
                        c.close()
                        print("Connection disconnected.")
                        break
                        
                    if confirm == 'N':
                        server_data = "Rejected"
                        server_data = encrypt(password, server_data)
                        c.send(server_data.encode())
                        c.close()
                        print("Connection disconnected.")
                        break
                
                if (266-q.current_size()) < data[2]:
                    print("You do NOT have the capacity for them.")
                    server_data = "Rejected"
                    server_data = encrypt(password, server_data)
                    c.send(server_data.encode())
                    c.close()
                    print("Connection disconnected.")
                    break
                
            else:
                print("Wrong secret key.")
                server_data = "No access"
                server_data = encrypt(password,server_data)
                c.send(server_data.encode())
                c.close()
                print("Connection disconnected.")
                break
                
        except:
            print("Wrong secret key.")
            server_data = "No access"
            server_data = encrypt(password,server_data)
            c.send(server_data.encode())
            c.close()
            print("Connection disconnected.")
            break

    
if menu_option == '2':
    if q.dequeue() == "Queue is empty!":
        print(q.dequeue())
        s.close()
        print("Connection disconnected.")
    else:
        num = int(input("How many to dequeue: "))
        for i in range(num):
            q.dequeue()
        print("Items in queue now are:")
        q.display()
        s.close()
        print("Connectiom disconnected.")

## Client
password = input("Please type the password: ")
team_name = input("What is your Team name: ")
group_size = int(input("Group size: "))

client_data = [password, team_name, group_size]
client_data = str(client_data)

from socket import socket

s = socket()

print("Establishing connection...")
port = 12345
s.connect(('localhost', port))
print("Connection established!")

client_data = encrypt(password, client_data)
s.send(client_data.encode())
print("Data sent!")

print("Waiting for the server to confirm your request...")
data = s.recv(4096).decode()
data = decrypt(password, data)

if data == "Accepted":
    print("Pickup confirmed! Please wait for pickup.")
    s.close()
    print("Connection disconnected.")
    
elif data == "Rejected":
    print("Pickup rejected!")
    print("Wrong password or request rejected.")
    print("Please try again.")
    s.close()
    print("Connection disconnected.")
    
else:
    print("Pickup cancelled.")
    print("Wrong password or request rejected.")
    print("Please try again.")
    s.close()
    print("Connection disconnected.")