Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- from Crypto.PublicKey import RSA
- from Crypto import Random
- from Crypto.Cipher import AES
- from Crypto.Util.Padding import pad, unpad
- from Crypto.Cipher import PKCS1_OAEP
- class Server:
- __sock = None
- __connection = None
- __session_key = None
- def __init__(self, host, port):
- self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.__sock.bind((host, port))
- def handshake(self):
- keys = RSA.generate(1024, Random.new().read)
- rsa_private_key = PKCS1_OAEP.new(RSA.importKey(keys.exportKey("PEM")))
- self.__connection.send(keys.publickey().exportKey(format='PEM', passphrase=None, pkcs=1))
- self.__connection.send(bytes("\n", 'utf-8'))
- resp = self.__connection.recv(1000)
- test = rsa_private_key.decrypt(resp)
- self.__session_key = AES.new(test, AES.MODE_ECB)
- def send_msg(self, data):
- data = self.__session_key.encrypt(pad(bytes(data, 'utf-8'), 16))
- self.__connection.send(data)
- def run(self):
- self.__sock.listen(1)
- print("Waiting for client")
- self.__connection, addr = self.__sock.accept()
- print(f"connected to {addr[0]}:{addr[1]}")
- self.handshake()
- while True:
- msg = input("Server: ")
- self.send_msg(msg)
- resp = self.__connection.recv(1000)
- data = unpad(self.__session_key.decrypt(resp), 16)
- print(f"Client: {data}")
- server = Server("127.0.0.1", 9001)
- server.run()
Add Comment
Please, Sign In to add comment