我试图在python中使用AES-256加密json文件。使用以下代码,但出现错误"TypeError: BufferedReader类型的对象不能被JSON序列化“。
import json
from Cryptodome.Cipher import AES
with open('filename.json','rb') as f:
text=json.dumps(f)
key = 'QWE1ER2T3Y4U4I5O5PAD2SFH4JK3HX4Z'
IV= 'QWE1ER2T3Y4U4I5O'
mode = AES.MODE_CBC
encryptor = AES.new(key.encode('utf8'), mode,IV=IV.encode('utf8'))
ciphertext = encryptor.encrypt(text)Json档案:
{
"user_id": "321871616",
"name": "test",
"phone_number": "9985623587",
"token": "Bearer 4df8d0af-3b51-4c07-a9e1-b7cee519d169 ",
"email": "test@test.com",
"data": {
"launchPoint": "getMore",
"journeyType": "prePurchase",
"sourceURL": "https://www.google.com",
"successRedirectURL": "https://www.fb.com",
"productCode": "OPD",
"customerType": "PP",
"ppCustomerEligible": true,
"ppBalance": 500.00,
"appType": "native",
"device": {
"androidId": "s",
"make": "qw",
"firebaseId": "s",
"advertisingId": "d",
"installId": "d",
"imei": "d",
"model": "d",
"deviceId": "d",
"deviceType": "android",
"os": {
"osName": "1d2",
"osVersion": "df",
"appVersion": "df"
}
}
}
}发布于 2022-01-13 15:18:17
您不需要使用json.loads将json文件读入dict中。函数Cryptodome.Cipher.EcbMode.encrypt(self, plaintext, output=None)需要字节或字节数组作为参数plaintext,因此在传递dict时,它会引发一个错误"TypeError: BufferedReader类型的对象不能被JSON序列化“。只需将文件内容以字节形式读取并加密:
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)然后我们可以将ciphertext打印为base64格式:
import base64
base64_ciphertext = base64.b64encode(ciphertext).decode("ascii")
print(base64_ciphertext)https://stackoverflow.com/questions/70698283
复制相似问题