Демонстрируется на упрощенном пользовательском подходе шифрования / дешифрования (с использованием библиотеки simple-crypt
):
Образец input.txt
Содержание:
first line
second line
last line
server.py
:
import socket
from simplecrypt import encrypt, decrypt
HOST = '127.0.0.1'
POST = 11200
pwd = 'secret' # for demo only
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST, POST))
sock.listen(1)
conn, addr = sock.accept()
with conn:
print(f'Got connection from {addr}')
while True:
data = conn.recv(1024)
if not data:
break
print(f'Received data from client {data}')
conn.send(decrypt(pwd, data))
client.py
:
import socket
from simplecrypt import encrypt, decrypt
import time
HOST = '127.0.0.1'
POST = 11200
pwd = 'secret' # for demo only
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, POST))
with open('input.txt', 'rb') as f:
for line in f:
sock.send(encrypt(pwd, line.strip()))
time.sleep(1) # the needed delay
data = sock.recv(1024).decode('utf8')
print(f'Received data from server "{data}"')
Процесс запуска сокета-сервера и вывод:
[roman@roman-pc data]$ python3 server.py
Got connection from ('127.0.0.1', 40736)
Received data from client b"sc\x00\x02p\x02\x98\xd4@\x9e\xeaeb@u\xc5\xbc\x0b\xbea\xcf\xca~\x87\xb1\x01(\x9d\xd2\x05\x0b8\xa8\x85\x94\xc4\xc5\xe2W\x8d\xe5P\xec\x83D\xeb\xe8\xcbV\x1ai3\xf5\x13s\x82\xbe7\xc9\xa8\xad'e\xbeq&Q_\x0f\t~V\x13\xe9\xde\xf1\xba~"
Received data from client b'sc\x00\x02Sa\xe9\x97,\xf7\x99\x7f<\xd2n\xbfc\x98g~t\xa3\xf9\x98\xc9\xf9\xff>\x99\x9aI{sAMY"\x9bX\x19\xfe\xe3i\xad=\xfa\rs\x9b,\xaadN\xb9_Bc\xe2\xf75\xdfP/wx\x1a\x91\xa27VZ[M\xa3\x0f3\xc9vL'
Received data from client b'sc\x00\x02U\xb8\xbc|\xbb\xbe\x95\xd5\\}0}\x8a\x10^]\xa0\xc9S\x08a\x99\x8e\xdd7[\xa4q\xec|\xe3\xe1\xf9|\xca?\x07\x18\xbc\xb4^*`\x7f\x07)\x1b\x10&\xda\xfdl!O\xa5K\xbe.\xd4\xbe\xb0\x960\x81\x83\xcb\x07\xb0=\x95\x8f\xd5\xb5'
Запуск и вывод процесса Socket-клиента (отправка зашифрованного сообщения с необходимой задержкой):
[roman@roman-pc data]$ python3 client.py
Received data from server "first line"
Received data from server "second line"
Received data from server "last line"