1 year ago

#372304

test-img

Emonale

Python AES 256 CBC Base64 decryption not working

I'm trying to decipher a string downloded from a server. The text contains JSON, e.g., {"test": {"value_1": "my_value_1","value_2": "my_value_2"}}. If I encode it using AES CBC 256, a test key = 12345678123456781234567812345678 and a test IV = 1234567812345678, the encoded text is AFuY54CNGKerwFIBogtRlL+fw9LKQmURPl5XsR3wOtVhvbRmy9D6o7xLq8HRTj69GSED3R+Wa0y4nnJfuQvQgQ==. I've tried decoding it in Java and it works fine, but in Python I get the UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 0: invalid start byte error message. This is the code I use, including padding and unpadding. For the pad, I add the '=' char to the end of the Base64 string. I have also tried specifying a few different encodings (utf-8, utf-16, ascii) but it never works.

def un_pad(data):
    return data[0:-data[-1]]

def pad_base64(string):
    while len(string) % 16 != 0:
        string += '='
    return string

if __name__ == '__main__':
    test_string_base64 = "AFuY54CNGKerwFIBogtRlL+fw9LKQmURPl5XsR3wOtVhvbRmy9D6o7xLq8HRTj69GSED3R+Wa0y4nnJfuQvQgQ=="

    test_IV = "1234567812345678".encode()
    test_KEY = "12345678123456781234567812345678".encode()

    test_string_base64_padded = pad_base64(test_string_base64)

    test_string_base64_padded_encoded = test_string_base64_padded.encode()

    decipher = AES.new(key=test_KEY, mode=AES.MODE_CBC, IV=test_IV)
    decoded_base64_data_padded = decipher.decrypt(test_string_base64_padded_encoded)

    decoded_base64_data_unpadded = un_pad(decoded_base64_data_padded)

    decoded_data = decoded_base64_data_unpadded.decode("UTF-8")

python

json

base64

aes

cbc-mode

0 Answers

Your Answer

Accepted video resources