使用 Python 对 json 文件进行 AES-256 加密

AES-256 encryption of a json file using Python

我正在尝试使用 python 中的 AES-256 加密 json 文件。使用以下代码但出现错误“TypeError: Object of type BufferedReader is not JSON serializable”。

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"
      }
    }
  }
}

您不需要使用 json.loads 将 json 文件读入字典。 函数 Cryptodome.Cipher.EcbMode.encrypt(self, plaintext, output=None) 需要字节或字节数组作为参数 plaintext,因此当您传递字典时它会引发错误“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)