0

I'm trying to encrypt and decrypt values, using python pycryptodome, saved to my Postgresql database on the client side based on example 2 found here; SymmetricEncryptionClientSide. However, I keep running into UnicodeDecodeErrors, such as the following one;

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 0: invalid start byte

This is my code;

nonce = uuid.uuid4().bytes
str_key = "wq5RdHHfzCW1/2eE" # example key

def sym_encrypt(data):
    key = str_key.encode("utf-8")
    cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
    data = data + (" " * (16 - (len(data) % 16)))
    return cipher.encrypt(data.encode("utf-8")).hex()


def sym_decrypt(data):
    key = str_key.encode("utf-8")
    cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
    return cipher.decrypt(binascii.unhexlify(data)).decode("utf8").rstrip()

nounce is used to ensure that all the same values have the same encryption string for querying purposes. It's the same reason why the values get Hex.

When performing the encryption on a string value such as; test@test.com using the encryption function above I get the following string saved to my database; 938174e09f8411a4957b7b91e07162b4 which is a string

However, when I perform the decrypt part as shown above I get the UnicodeDecodeError error.

For more information;

this is what the value looks like after encoding and before encryption and hex:

b'test@test.com '

This is what the value looks like after encoding and encryption and before hex:

b'\x92\xa1\xe1\x06\xd1\xd8\x8c\xbdv0\xb2\x13p!$#'

When encoding the value before decryption the value looks like:

b'938174e09f8411a4957b7b91e07162b4'

But after unhexlify the value the byte looks different to the byte after encryption:

b'\x93\x81t\xe0\x9f\x84\x11\xa4\x95{{\x91\xe0qb\xb4'

I'm not sure what is happening here. I expected the byte to look the same after encryption and when unhexlify, but this is not the case. When I perform the decrypt I get the 'UnicodeDecodeError error.

Does anyone know why this is happening and how to solve this issue? Thanks in advance.

Kakedis
  • 172
  • 8
  • 2
    I ran your code with added imports and code to actually call encrypt/decrypt and it worked correctly. make a [mcve] that reproduces the issue that can be copied and run without additional changes. the problem is in code not shown. – Mark Tolonen Jul 22 '22 at 22:16
  • Thanks @MarkTolonen. You were right, the issue was not related to the encryption/decryption, but rather with my database field and the TypeDecorator I was using. – Kakedis Jul 25 '22 at 20:44

0 Answers0