AES-256 encryption of a json file using Python
You do not need to read the json file into a dict using json.loads.
Function Cryptodome.Cipher.EcbMode.encrypt(self, plaintext, output=None)
requires bytes or bytearray as parameter plaintext
, so it raised an error "TypeError: Object of type BufferedReader is not JSON serializable" when you passed a dict.
Just read the content of file as bytes and encrypt it:
import json
from Cryptodome.Cipher import AES
with open('filename.json','rb') as f:
text = f.read()
key = 'QWE1ER2T3Y4U4I5O5PAD2SFH4JK3HX4Z'
IV= 'QWE1ER2T3Y4U4I5O'
mode = AES.MODE_CBC
encryptor = AES.new(key.encode('utf8'), mode,IV=IV.encode('utf8'))
length = 16 - (len(text) % 16)
cbc_pad_text = text + bytes([length])*length # pad to 16 byte boundary in CBC mode
ciphertext = encryptor.encrypt(cbc_pad_text)
Then we can print ciphertext
as base64 format:
import base64
base64_ciphertext = base64.b64encode(ciphertext).decode("ascii")
print(base64_ciphertext)