#!/usr/bin/env python3 # coding: utf8 import json import logging import logging.config import os import socket #### logging #### # json decoder for int keys import threading from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP class Decoder(json.JSONDecoder): def decode(self, s, **kwargs): result = super().decode(s) # result = super(Decoder, self).decode(s) for Python 2.x return self._decode(result) def _decode(self, o): if isinstance(o, str): try: return int(o) except ValueError: return o elif isinstance(o, dict): return {k: self._decode(v) for k, v in o.items()} elif isinstance(o, list): return [self._decode(v) for v in o] else: return o def setup_logging(default_path='log_config.json', default_level=logging.INFO, env_key='LOG_CFG'): """Setup logging configuration """ path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: config = json.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level) setup_logging() log_server = logging.getLogger('server') debug = log_server.debug info = log_server.info warning = log_server.warning error = log_server.error critical = log_server.critical #### Variables #### HOST = '127.0.0.1' PORT = 8888 BUFFER_SIZE = 4096 clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientSocket.connect((HOST, PORT)) # ET ICI ON MET LE CLIENT BEGIN_MESSAGE = bytes("debut", "ascii").ljust(BUFFER_SIZE, b";") END_MESSAGE = bytes("fin", "ascii").ljust(BUFFER_SIZE, b";") HEADER_TXT = """\ EICP2P2 V1 type: RSASend""" HEADER = bytes(HEADER_TXT, "ascii").ljust(BUFFER_SIZE, b";") ## création des clef RSA print(1024) key = RSA.generate(BUFFER_SIZE) private_key = key.export_key() file_out = open("private.pem", "wb") file_out.write(private_key) public_key = key.publickey().export_key() file_out = open("receiver.pem", "wb") file_out.write(public_key) to_send = public_key.ljust(BUFFER_SIZE, b';') clientSocket.send(BEGIN_MESSAGE) clientSocket.send(HEADER) clientSocket.send(to_send) clientSocket.send(END_MESSAGE) print('ok') # BEGIN chunk = clientSocket.recv(BUFFER_SIZE) print(chunk) # HEADER crypted = clientSocket.recv(BUFFER_SIZE).rstrip(b';') # AESKEY for i in range(60): crypted += clientSocket.recv(BUFFER_SIZE).rstrip(b";") # END chunk = clientSocket.recv(BUFFER_SIZE) print(chunk) # HEADER+AES key are encypted in same time, so decrypt thme at same time cipher_rsa = PKCS1_OAEP.new(key) texte = b'' for to_decrypt in [crypted[i:i + int(BUFFER_SIZE/8)] for i in range(0, len(crypted), int(BUFFER_SIZE/8))]: texte += cipher_rsa.decrypt(to_decrypt) print(texte.decode('ascii'))