Python: Can Json Be Used To Send A Message To A Python Server Which Contains Encrypted Sections?
Solution 1:
You can simply encrypt the JSON and send the ciphertext as raw binary data.
JSON is just a format; no-one is forcing you to send it over the wire.
Solution 2:
Yes,
but certain strings must be escaped prior to sending it and then unescaped at the other end.
Either by from base64 import b64encode, b64decode
or something similar.
The reasons for this is that the JSON data MUST be string or int values, nothing else basicly.
json.dumps({1 : 2, 'hey' : 'you'})
will work and that's the format you need to keep it. meaning binary data might mess with json as it expects "normal" strings. b64encode ensures that it's only valid characters in the string and nothing else :)
Depending on what you're trynig to acomplish. You can also encrypt the entire JSON string and send that to the server, decrypt it and parse it as JSON.
See the encryption as a tunnel.
JSON -> encrypt(JSON-string) -> server -> decrypted -> parse JSON
Or if you need the JSON data as meta data, do the first option.
This is a way to encapsulate ALL traffic as "encrypted"
def encrypt(s):
encryptedString = AES.encrypt(s)
return b64encode(encryptedString)
sock.connect(server)
jsondata = {1 : 2}
sock.send( encrypt(json.dumps(jsondata)) )
And on the server you just do:
data = sock.recv(1024)
jsondata = json.loads( b64decode(decrypt(data))) )
print(jsondata)
This is a way to encrypt only SOME parts of the json data:
def encrypt(s):
encryptedString = AES.encrypt(s)
return b64encode(encryptedString)
sock.connect(server)
jsondata = {1 : encrypt(2)}
sock.send( json.dumps(jsondata) )
And on the server:
data = sock.recv(1024)
jsondata = json.loads(data)
jsondata[1] = decrypt(b64decode(jsondata[1]))
Post a Comment for "Python: Can Json Be Used To Send A Message To A Python Server Which Contains Encrypted Sections?"