CryptoFly.us | CRYPTOCURRENCY BITCOIN SHIRTS CLOTHING APPAREL HATS

CRYPTO NEWS

Proshares’ Bitcoin ETF sees $1B in first day volume, BTC price hits new high, and Coinbase partners with NBA and WNBA: Hodler’s Digest, Oct. 17-23

Why I’m getting ValueError while trying to unpad the data? [closed]

In short, I’m developing an encrypted chat using ECDH + AES. All encrypting and decrypting algorithms work just fine when I’m testing them separately. They are also working when there is established only one connection to the server. However, when there is more than one socket connected, I’m getting this error. Traceback (most recent call::Listen

In short, I’m developing an encrypted chat using ECDH + AES.

All encrypting and decrypting algorithms work just fine when I’m testing them separately.
They are also working when there is established only one connection to the server.
However, when there is more than one socket connected, I’m getting this error.

Traceback (most recent call last):
  File "C:UsersuserAppDataLocalProgramsPythonPython39libthreading.py", line 973, in _bootstrap_inner
    self.run()
  File "C:UsersuserAppDataLocalProgramsPythonPython39libthreading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
  File "C:!GitLabchatclient.py", line 111, in listener
    plaintext = self.client_cred.decrypt(
  File "C:!GitLabchatecdh.py", line 105, in decrypt
    return unpadder.update(decrypted_data) + unpadder.finalize()
  File "C:UsersuserAppDataLocalProgramsPythonPython39libsite-packagescryptographyhazmatprimitivespadding.py", line 159, in finalize
    result = _byte_unpadding_check(
  File "C:UsersuserAppDataLocalProgramsPythonPython39libsite-packagescryptographyhazmatprimitivespadding.py", line 101, in _byte_unpadding_check
    raise ValueError("Invalid padding bytes.")
ValueError: Invalid padding bytes.

And here is encrypt my code of en/decryption:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from secrets import token_bytes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec

FORMAT = 'utf-8'
BLOCK_SIZE = 16


class DH:
    def __init__(self):
        self.ECDH = ec.generate_private_key(ec.SECP384R1(), default_backend())
        self.public_key = self.ECDH.public_key()

    def encrypt(self, public_key, plaintext):
        """
        IV = 16 bytes
        SALT = 16 bytes
        Shared key = 48 bytes
        Derived key = 32 bytes

        AES = 256 bits
        AES = 32 bytes

        Padder = 128 or 256 bits
        Padder = 16 or 32 bytes

        Ciphertext = IV + SALT + MSG

        :param public_key: another client public key
        :param plaintext: a text to be encrypted
        :return: encrypted ciphertext
        """
        IV = token_bytes(16)
        SALT = token_bytes(16)
        shared_key = self.ECDH.exchange(ec.ECDH(), public_key)

        derived_key = HKDF(
            algorithm=hashes.SHA256(),
            length=32,
            salt=SALT,
            info=None
        ).derive(shared_key)

        encryptor = Cipher(
            algorithms.AES(derived_key),
            modes.CBC(IV)
        ).encryptor()
        
        # unpadder = padding.PKCS7(256).unpadder()
        padder = padding.PKCS7(128).padder()
        padded_data = padder.update(plaintext.encode(FORMAT)) + padder.finalize()

        return IV + SALT + encryptor.update(padded_data) + encryptor.finalize()

    def decrypt(self, public_key, ciphertext):

        IV = ciphertext[:16]
        SALT = ciphertext[16:32]
        ciphertext = ciphertext[32:]

        shared_key = self.ECDH.exchange(ec.ECDH(), public_key)

        derived_key = HKDF(
            algorithm=hashes.SHA256(),
            length=32,
            salt=SALT,
            info=None
        ).derive(shared_key)

        decryptor = Cipher(
            algorithms.AES(derived_key),
            modes.CBC(IV)
        ).decryptor()

        decrypted_data = decryptor.update(ciphertext) + decryptor.finalize()
        
        # unpadder = padding.PKCS7(256).unpadder()
        unpadder = padding.PKCS7(128).unpadder()
        return unpadder.update(decrypted_data) + unpadder.finalize()

The server receives a message:

msg = current_client.recv(2048)

Decrypts it:

plaintext = self.serv_cred.decrypt(
                    self.connection_dic.get(current_client),
                    msg
                ).decode(FORMAT)

Encrypts it using the clients’ pub keys (which are stored in a dictionary) and sends it to the chat members:

for client, pub_k in self.connection_dic.items():
    ciphertext = self.serv_cred.encrypt(pub_k, plaintext)
    client.send(ciphertext)

The client-side receives a message:

msg = self.client_socket.recv(2048)

Decodes it:

plaintext = self.client_cred.decrypt(
                            self.server_public,
                            msg
                        ).decode(FORMAT)

The client-side encryption looks like

ciphertext = self.client_cred.encrypt(
                    self.server_public,
                    msg
                )

The problem in more details:

Only Client1 is connected to the server and sends a message:

msg = 'This is a test message, when only one socket is connected!'

enc IV b'xc9xc3`xdexe0^x87xf0Ox93x11} xb9xebx8b'
enc SALT b'xebs\xc8x82xccxcbx88xb1xeax99x92lfQx18'
enc Shared b'x82xf0~xa5-txf4x00xcbxa9xfdx16x10x81lxd7[qX]Sxe7@h3Fix14OIox8exd5_xb7xb4lxb1xc8L:x9e;xafxc6gx17s'
enc Derived b'xadx0fWx8bW[x86^xe3xc2xe5x1axc0NoYnx1ex03x19x1d@!$zw]xafx85xa8x9dxc5'
enc Padded b'This is a test message, when only one socket is connected!x06x06x06x06x06x06'

Server decrypts a message of Client1 without any problem:

dec IV b'xc9xc3`xdexe0^x87xf0Ox93x11} xb9xebx8b'
dec SALT b'xebs\xc8x82xccxcbx88xb1xeax99x92lfQx18'
dec Ciphertext b'j*xd8Q@ZGd\9xe3Qx;}xfaxa9ex16xb4xd0x8cxabxa0xc2kx11x87xf0Fxd5xbax8brxf27xd9xa0xf1xd3Zx99x18!xeexa9xd4x8bxfcxf0x19x87xeex07x91xf1x10x8cxfbxd6xb9xf7x1cx86'
dec Shared b'x82xf0~xa5-txf4x00xcbxa9xfdx16x10x81lxd7[qX]Sxe7@h3Fix14OIox8exd5_xb7xb4lxb1xc8L:x9e;xafxc6gx17s'
dec Derived b'xadx0fWx8bW[x86^xe3xc2xe5x1axc0NoYnx1ex03x19x1d@!$zw]xafx85xa8x9dxc5'
dec Unpadded b'This is a test message, when only one socket is connected!'
alice says This is a test message, when only one socket is connected!

Now Client2 is also connected and send a message:

msg = 'This is a test message when a second socket is trying to send a message!'

enc IV b';:Hxcdhh^ xf9x1dxd2Fx85xf6x10x04'
enc SALT b'xfc)x11x1ex97Co)xd4xd2xb8MXxe9x08xac'
enc Shared b'Rx8excaxcfxe0Axd0{^)x84x82xc1xe1:7xe9x852exbfx88kxe5xa0x18Vx17?v;xd1xb9xf76+[xfdxc1gpxaanFx9dYxeax82'
enc Derived b"x18xaa>xe5Ttx89TDnxc3V(txa2Vxc9x08xb5x8a'xe9xaepx19{x94Ck1_b"
enc Padded b'This is a test message when a second socket is trying to send a message!x08x08x08x08x08x08x08x08'

The server decrypts it (same IV, SALT, Shared and Derived key):

dec IV b';:Hxcdhh^ xf9x1dxd2Fx85xf6x10x04'
dec SALT b'xfc)x11x1ex97Co)xd4xd2xb8MXxe9x08xac'
dec Ciphertext b"xaf'x8axf2x1dx9ddx93xc4xa9xc5Ex19xebxa9GxdexaeBxefux7fxc0SWx0fx15|xa5xeex1bx19Pxfax9ax9fx88xf2xf9x10xcaeGqrxfcxb6xfb!xc9}xd8ex14xfaxc4mxxaevx03%xf8xc4xaex9exe7x16Zx05xc9xccxc8x05xc5oR]xecd"
dec Shared b'Rx8excaxcfxe0Axd0{^)x84x82xc1xe1:7xe9x852exbfx88kxe5xa0x18Vx17?v;xd1xb9xf76+[xfdxc1gpxaanFx9dYxeax82'
dec Derived b"x18xaa>xe5Ttx89TDnxc3V(txa2Vxc9x08xb5x8a'xe9xaepx19{x94Ck1_b"
dec Unpadded b'This is a test message when a second socket is trying to send a message!'

The server encrypts a message and sends it to Client1:

msg = 'bob > This is a test message when a second socket is trying to send a message!'
enc IV b'x82`Pvxc3xacxacx95xd75xd8xd0XLx10#'
enc SALT b'xe5?yxaex1cxbeMIsx92xe3x0e1x07Bxf1'
enc Shared b'xc70}6Yxacxdcxa4x87xbax85xc2x0cxd8x88x85_e#x83fxa1xb0(xacx94s$txfdx0bennxa6xbfzx1ax9byTtxa8xffkxd9xcbxb5'
enc Derived b'pxefxb2xebxb9Nx0eQxa8q(x04Vx91Ix841xecxddx04mxd2xef?x02x98f@Bx80xd0x16'
enc Padded b'bob > This is a test message when a second socket is trying to send a message!x02x02'

Client1 gets same IV and SALT from server. However he doesn’t manage to generate same Shared key and ValueError is raised:

dec IV b'x82`Pvxc3xacxacx95xd75xd8xd0XLx10#'
dec SALT b'xe5?yxaex1cxbeMIsx92xe3x0e1x07Bxf1'
dec Ciphertext b"xd9xcd)!xdexe8ksx91kCxe8xbax96xe1x1eyH.Dxffxecxbex82xf3x88x0bTxd56@Ax05x12xaexb2xccxd7yx0fmb,xadxabxf5xc5xdcxe0%xcexf9`x02x80kxa5xadxaa|7[%x0ex0bpxb2xebxb9'xa3x1bxb8!ixb6xcbSxe4x1d"
dec Shared b'x82xf0~xa5-txf4x00xcbxa9xfdx16x10x81lxd7[qX]Sxe7@h3Fix14OIox8exd5_xb7xb4lxb1xc8L:x9e;xafxc6gx17s'
dec Derived b'Qx0bxe0xcfYx869bx8axa7x91x02xefxb5x01xa9h_Zx16Ixe5Qxrx93xf3xec-xabKx91'
ValueError

Proshares’ Bitcoin ETF sees $1B in first day volume, BTC price hits new high, and Coinbase partners with NBA and WNBA: Hodler’s Digest, Oct. 17-23

Shopping cart
There are no products in the cart!
Continue shopping
0