pythonpython-cryptographyfernet

How to decrypt a string with fernet as a flask service?


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.


Solution

  • You're passing fernet.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 fernet algorithm every time the program starts, means that if your server restarts, all of the data is gone.