0

I use AES-256 refer Encrypt & Decrypt using PyCrypto AES 256. However there is a some error while decoding.

  File "/home/client.py", line 60, in receive
    print('%s :' %opp_id, aes.decrypt(recvData))
  File "/home/client.py", line 31, in decrypt
    return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
  File "/home/PycharmProjects/qkd-chat/venv/lib/python3.9/site-packages/Crypto/Cipher/blockalgo.py", line 295, in decrypt
    return self._cipher.decrypt(ciphertext)


ValueError: Input strings must be a multiple of 16 in length

The code below is part for AES-256.

class AESCipher(object):
    def __init__(self, key):
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

this is the part of socket programming

def send(sock):
    while True:
        try:
            aes = AESCipher(key)
            sendData = aes.encrypt(input())
            # sendData = encrypt(key, input())
            sock.send(sendData)
        except:
            continue
def receive(sock):
    while True:
        recvData = sock.recv(4096)
        try:
            aes = AESCipher(key)
            print('%s :' %opp_id, aes.decrypt(recvData))
        except DecryptionException as e:
            print(e)

I think there is an error in receive message because there is a some change in error message when I change the number in sock.recv( - )

qwerty
  • 27
  • 4
  • 2
    Just because you're trying to receive 4096 bytes doesn't mean you'll get the message in one chunk. You need to receive until there's nothing more to receive, or first send the length and in the receiver get the length then recv until you receive that many bytes. You can diagnose by printing the length as sent and as received. – DisappointedByUnaccountableMod Nov 22 '21 at 12:46
  • Does this answer your question? [Why does server and client gets out of sync? (python sockets)](https://stackoverflow.com/questions/55160527/why-does-server-and-client-gets-out-of-sync-python-sockets) - see in particular the para starting "The only reliable way to handle TCP sockets..>" – DisappointedByUnaccountableMod Nov 22 '21 at 14:18

0 Answers0