我正在实施RSA加密/解密。要加密的数据包含不同的数据类型。因此,我在python中使用了字典。但是我遇到了错误。我正在附上代码片段。请提供解决方案!谢谢。
import base64
from cryptography.fernet import Fernet
import os
import hashlib
from cryptography.hazmat.backends import default_backend
from Crypto.PublicKey import RSA
from cryptography.hazmat.primitives.asymmetric import padding
from Crypto import Random
class SplitStore:
....
def encrPayload(self, payload):
modulus_length = 256 * 13 # use larger value in production
privatekey = RSA.generate(modulus_length, Random.new().read)
public_key = privatekey.publickey()
private_pem = privatekey.exportKey().decode()
with open('private_pem.pem', 'w') as pr:
pr.write(private_pem)
byte_payload = payload.encode('utf-8', 'strict')
#print("Byte Payload:{} ".format(byte_payload))
encrypted_payload = public_key.encrypt(byte_payload, 32)[0]
#print("type:{}".format(type(encrypted_payload)))
#print("\nEncrpted METADATA: {}".format(encrypted_payload))
bchain_file = open("blockchain/file.dat", "wb")
bchain_file.write((encrypted_payload))
def createMetaData(self):
time_stamp = os.stat("/home/pc-01/sample.pdf").st_ctime
#print("\nTIMESTAMP: {}".format(time_stamp))
hash_data = hashlib.sha512(self.pdfReader).hexdigest()
#print("\nHASHDATA : {}".format(hash_data))
secret_keys = self.j #j is a list of keys
#print("List of secret keys: {}".format(self.j))
#print("String conv: " + str(secret_keys[0]))
#Creating a dictionary
payload = {
"time_stamp" : time_stamp, #int
"hash" : hash_data, #string
"keys" : secret_keys #list
}
#print("\nPAYLOAD: " + payload)
return payload
...
def main():
s1 = SplitStore()
s1.initializeData()
...
if __name__ == "__main__":
main()
secret_keys
中的 payload
是一个包含字节格式密钥的列表。运行代码后,出现以下错误:
Traceback (most recent call last):
....... chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode return _iterencode(o, 0)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'Vm3pb7XRJ4W_8M1ShKHAGiuDa2PT1DN_0ncjf0hmNJU=' is not JSON serializable
有什么办法解决这个问题?
答案 0 :(得分:0)
如果问题不是如下所述的bytes
引起的,则可以通过遵循this answer并找出哪些变量无法序列化来缩小导致问题的原因。
您在secret_keys
中的项目是bytes
,它们不能JSON序列化。因此,您必须将它们转换为普通的str
对象。您可以通过decode
方法执行以下操作:
plainstr = bytestr.decode("utf-8")
# The encoding passed need not be "utf-8", but it is quite common
类似地,您可以encode
到str
到bytes
,如下所示:
encodedstr = plainstr.encode("utf-8")