seg/trabalho4/service.py

71 lines
1.7 KiB
Python

import socket
from common import *
import socket
from AES import AESCipher
import os
from random import randint
import base64
HOST = "127.0.0.1"
PORT = SERVICE_PORT
SERVICE_KEY = os.urandom(32)
def process_message(message):
print(message)
message = message.split("||")
if message[0] == "getkey":
return f"{base64.b64encode(SERVICE_KEY)}"
if message[0] == "request":
"""
T_c_s = {ID_C + T_A + K_c_s}K_s
M5 = [{ID_C + T_A + S_R + N3}K_c_s + T_c_s]
M6 = [{Resposta, N3}K_c_s]
"""
body = message[1].split("<>")
K_s = SERVICE_KEY
T_c_s_AES = AESCipher(K_s)
M5_inner = body[0]
T_c_s = body[1]
T_c_s = T_c_s_AES.decrypt(T_c_s)
T_c_s = T_c_s.split("<>")
ID_C = T_c_s[0]
T_A = T_c_s[1]
K_c_s = eval(T_c_s[2])
M5_inner_AES = AESCipher(K_c_s)
M5_inner = M5_inner_AES.decrypt(M5_inner)
M5_inner = M5_inner.split("<>")
ID_S = M5_inner[2]
N3 = M5_inner[3]
# generate M6
M6_inner = f"{randint(0, 100)}<>{N3}"
M6_inner_AES = AESCipher(K_c_s)
M6_inner = M6_inner_AES.encrypt(M6_inner)
M6 = f"{M6_inner}"
return M6
def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
all_data = ""
data = conn.recv(4096)
all_data += data.decode()
response = process_message(all_data)
conn.sendall(response.encode())
if __name__ == "__main__":
main()