I am making a simple flask api which is encoding and decoding the coming string. I have no problem with encoding but I am getting InvalidToken error when decoding. I tried smth.but could not make it. Code:
from flask import Flask,jsonify,request
from cryptography.fernet import Fernet
app = Flask(__name__)
key = Fernet.generate_key()
fernet = Fernet(key)
@app.route('/decode',methods = ["POST"])
def decode():
response = {'encoded_text': request.json['encoded_text']}
text = response['encoded_text']
print(text)
decryptedbytes = fernet.decrypt(text)
decryptedstr = decryptedbytes.decode('utf-8')
return decryptedstr
if __name__ == '__main__':
app.run(debug=True)
Giving: TypeError: token must be bytes.
You're passing fe.net.decrypt
an str
instead of a bytes
object.
How is your encrypted data encoded within the JSON? The usual is a base64:
import base64
decryptedbytes = fernet.decrypt(base64.b64decode(text))
Keep in mind JSON does not support arbitrary bytes.
As a side note, generating a key for the fe.net algorithm every time the program starts, means that if your server restarts, all of the data is gone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.