I made these two encryption & decryption functions:
def encrypt(self, data, password, password2):
salt = get_salt()
key = scrypt(password, salt, 32, N=2 ** 14, r=8, p=1)
cipher = AES.new(key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(data.encode(), AES.block_size))
salt2 = get_salt()
key2 = scrypt(password2, salt2, 32, N=2 ** 14, r=8, p=1)
cipher2 = AES.new(key2, AES.MODE_CBC)
ct2_bytes = cipher2.encrypt(pad(ct_bytes, AES.block_size))
iv = base64.b64encode(cipher.iv).decode()
ct = base64.b64encode(ct2_bytes).decode()
salt = base64.b64encode(salt.encode()).decode()
salt2 = base64.b64encode(salt2.encode()).decode()
return f"{iv}:{ct}:{salt}:{salt2}"
def decrypt(self, data, password, password2):
iv, ct, salt, salt2 = data.split(":")
iv = base64.b64decode(iv)
ct = base64.b64decode(ct)
salt = base64.b64decode(salt).decode()
salt2 = base64.b64decode(salt2).decode()
key2 = scrypt(password2, salt2, 32, N=2 ** 14, r=8, p=1)
cipher2 = AES.new(key2, AES.MODE_CBC)
pt2 = unpad(cipher2.decrypt(ct), AES.block_size).decode()
key = scrypt(password, salt, 32, N=2 ** 14, r=8, p=1)
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
pt = unpad(cipher.decrypt(pt2.encode()), AES.block_size).decode()
return pt
Encryption is working fine for me, it's decryption that's the issue. Getting this error from line pt2 = unpad(cipher2.decrypt(ct), AES.block_size).decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 9: invalid start byte
I don't really understand encoding and decoding (conversion from chars to bytes??) so I appreciate any help with this.