-1

This question has already been answered here: How to encrypt JSON in python

However, I'm getting an error when using the cryptography module.

raise TypeError("{} must be bytes".format(name))
   TypeError: data must be bytes

Here's my code:

from cryptography.fernet import Fernet
key= b'F9tdtAlS5kqVL5_uxKCnOPailXUqKsJmxbHWGLv_H-c='

with open('info.json', 'rb') as loader1:
    params = json.load(loader1)

if xyz(x, y)==True:

        fernet = Fernet(key)
        encrypted=fernet.encrypt(params)
        print(encrypted)
        with open('info.json', 'wb') as writer1:
            json.dump(encrypted, writer1)
        
        print("Operation was a success")
else:
     print("error")
user13
  • 39
  • 7

1 Answers1

1

If you see in the original answer they are reading the contents from json file and not using json.load, so the content they are encrypting is in byte format however you are feeding in a json therefore the error data must be bytes. Quick fix will be to convert json to string using json.loads and then encoding to byte format before feeding it into fernet.encrypt()

To encode to byte https://www.geeksforgeeks.org/python-convert-string-to-bytes/

avisionx
  • 220
  • 1
  • 8