saleks28

bos3_server

Sep 15th, 2020
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. import socket
  2. from Crypto.PublicKey import RSA
  3. from Crypto import Random
  4. from Crypto.Cipher import AES
  5. from Crypto.Util.Padding import pad, unpad
  6. from Crypto.Cipher import PKCS1_OAEP
  7.  
  8. class Server:
  9.     __sock = None
  10.     __connection = None
  11.     __session_key = None
  12.  
  13.     def __init__(self, host, port):
  14.         self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  15.         self.__sock.bind((host, port))
  16.  
  17.     def handshake(self):
  18.         keys = RSA.generate(1024, Random.new().read)
  19.         rsa_private_key = PKCS1_OAEP.new(RSA.importKey(keys.exportKey("PEM")))
  20.         self.__connection.send(keys.publickey().exportKey(format='PEM', passphrase=None, pkcs=1))
  21.         self.__connection.send(bytes("\n", 'utf-8'))
  22.         resp = self.__connection.recv(1000)
  23.         test = rsa_private_key.decrypt(resp)
  24.         self.__session_key = AES.new(test, AES.MODE_ECB)
  25.  
  26.     def send_msg(self, data):
  27.         data = self.__session_key.encrypt(pad(bytes(data, 'utf-8'), 16))
  28.         self.__connection.send(data)
  29.  
  30.     def run(self):
  31.         self.__sock.listen(1)
  32.         print("Waiting for client")
  33.         self.__connection, addr = self.__sock.accept()
  34.         print(f"connected to {addr[0]}:{addr[1]}")
  35.         self.handshake()
  36.         while True:
  37.             msg = input("Server: ")
  38.             self.send_msg(msg)
  39.             resp = self.__connection.recv(1000)
  40.             data = unpad(self.__session_key.decrypt(resp), 16)
  41.             print(f"Client: {data}")
  42.  
  43.  
  44. server = Server("127.0.0.1", 9001)
  45. server.run()
  46.  
Add Comment
Please, Sign In to add comment