首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python对json文件进行AES-256加密

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

Stack Overflow用户
提问于 2022-01-13 14:29:17
回答 1查看 880关注 0票数 -1

我试图在python中使用AES-256加密json文件。使用以下代码,但出现错误"TypeError: BufferedReader类型的对象不能被JSON序列化“。

代码语言:javascript
复制
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档案:

代码语言:javascript
复制
{
  "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"
      }
    }
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-13 15:18:17

您不需要使用json.loads将json文件读入dict中。函数Cryptodome.Cipher.EcbMode.encrypt(self, plaintext, output=None)需要字节或字节数组作为参数plaintext,因此在传递dict时,它会引发一个错误"TypeError: BufferedReader类型的对象不能被JSON序列化“。只需将文件内容以字节形式读取并加密:

代码语言:javascript
复制
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格式:

代码语言:javascript
复制
import base64
base64_ciphertext = base64.b64encode(ciphertext).decode("ascii")
print(base64_ciphertext)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70698283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档