string decryption in python cipher is not working

49 views Asked by At

In my client-server app, I'm trying to encrypt strings, send, receive and decrypt. Maybe the order of unpadding and decrypting is wrong, or it does have something about deconding from ascii or uft-8, idk

client.py


import threading
import socket
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding

backend = default_backend()

block_size = 16 # tamanho do bloco da de msg, tem de ser multiplo de 16
key = os.urandom(32) # gerando uma key aleatoria para criptografar
iv = os.urandom(16) # vetor de inicialização

aes = algorithms.AES(key)
cbc = modes.CBC(iv)
cipher = Cipher(aes, cbc, backend=backend)
decryptor = cipher.decryptor() # decriptador
encryptor = cipher.encryptor() # encriptador

PORT = 7777
SERVER_IP = 'localhost'

def main():

    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        client.connect((SERVER_IP, PORT))
    except:
        return print('\nNão foi possível se conectar ao servidor!\n')

    username = input('Nome do usuário: ')
    print('\n',username,' conectado a ',SERVER_IP,' na porta ',PORT,'!\n')

    thread1 = threading.Thread(target=receiveMessages, args=[client])
    thread2 = threading.Thread(target=sendMessages, args=[client, username])

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()


def receiveMessages(client):
    while True:
        try:
            unpadder = padding.PKCS7(128).unpadder()

            msg_rcvd = client.recv(2048)
            print(f'encrypted msg received: {msg_rcvd}')
            
            dec_ct = decryptor.update(msg_rcvd) + decryptor.finalize()
            print(f'msg after decryption: {dec_ct}')

            msg_unpad = unpadder.update(dec_ct) #+ unpadder.finalize() #unpad antes ou depois??
            print(f'unpadded msg: {msg_unpad}')
            
        except Exception as e:
            print('\nNão foi possível permanecer conectado no servidor! Erro: ',e,'\n')
            print('Pressione <Enter> Para continuar...')
            client.close()
            break
            

def sendMessages(client, username):
    while True:
        try:
            padder = padding.PKCS7(128).padder()

            msg = input('\n')
            b_msg = bytearray(msg, encoding="ascii")
            n = len(b_msg)
            spaces_add = block_size - n % block_size
            new_b_msg = bytearray(msg + ' ' * spaces_add, encoding="utf8")
            padder = padding.PKCS7(128).padder()
            msg_pad = padder.update(new_b_msg) + padder.finalize()
            print(f'padded msg: {msg_pad}')
            ct = encryptor.update(msg_pad) + encryptor.finalize()
            try: #quero mandar em send's separados o username e a msg
                print(f'msg after encryption: {ct}')
                client.send(ct)
                # client.send(f'{username}: {msg_encrypted}'.encode('utf-8'))
            except Exception as e:
                print('error: ', e)
                
        except:
            return

main()

server.py Here I didn't mess with the recv method and broadcast and i don't think it is necessary

import threading
import socket


clients = []

PORT = 7777
SERVER_IP = 'localhost'

def main():

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        server.bind((SERVER_IP, PORT))
        server.listen()
        print('Servidor ligado em ', SERVER_IP, ' na porta ', PORT)
    except:
        return print('\nNão foi possível iniciar o servidor!\n')

    while True:
        client, addr = server.accept()
        clients.append(client)
        print(addr)
        thread = threading.Thread(target=messagesTreatment, args=[client])
        thread.start()

def messagesTreatment(client):
    while True:
        try:
            msg = client.recv(2048)
            broadcast(msg, client)
        except:
            clients.remove(client)
            print('deu errado e removeu', len(clients))
            break


def broadcast(msg, client):
    for clientItem in clients:
        if clientItem != client:
            try:
                clientItem.send(msg)
            except:
                clients.remove(client)

main()

Output: Message from client A:

test string padded msg: b'test string \x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10' msg after encryption: b'\x10\x980\xda\xf2\xc0\xce(d\xa6\x8f\t\x12i\xd0\x02\xd7\x80\x97\x0e\xdf\xa4\xb8^\xe2(\xdc\xb4t\xce*N'

Message received in client B:

encrypted msg received: b'\x10\x980\xda\xf2\xc0\xce(d\xa6\x8f\t\x12i\xd0\x02\xd7\x80\x97\x0e\xdf\xa4\xb8^\xe2(\xdc\xb4t\xce*N' msg after decryption: b'%\x1e\x95\x17_\xc6\x03\x88R\xf6#\xf9\xce\x1d^\x9c\xc5\xe6\x12\xdc\x15bkF\xbd\x84\xeb\xb9\xa4\xc4|\xea' unpadded msg: b'%\x1e\x95\x17_\xc6\x03\x88R\xf6#\xf9\xce\x1d^\x9c'

Expected output: b'\x10\x980\xda\xf2\xc0\xce(d\xa6\x8f\t\x12i\xd0\x02\xd7\x80\x97\x0e\xdf\xa4\xb8^\xe2(\xdc\xb4t\xce*N' msg after decryption: b'%\x1e\x95\x17_\xc6\x03\x88R\xf6#\xf9\xce\x1d^\x9c\xc5\xe6\x12\xdc\x15bkF\xbd\x84\xeb\xb9\xa4\xc4|\xea' unpadded msg: b'test string '

The encrypted message is received, as you can see, but the decryption and unpadding doesnt turn it to the original string.

0

There are 0 answers