secure-chat/client/main.py

125 lines
2.9 KiB
Python

#!/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
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
cry_header = clientSocket.recv(BUFFER_SIZE).rstrip(b';')
print(cry_header)
# AESKEY
cry_aeskey = clientSocket.recv(BUFFER_SIZE).rstrip(b";")
print(cry_aeskey)
# 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)
t = cry_header+cry_aeskey
for to_decrypt in [t[i:i + int(len(public_key)/16)] for i in range(0, len(t), int(len(public_key)/16))]:
print(len(to_decrypt))
print(cipher_rsa.decrypt(to_decrypt))