ValueError at / Fernet key must be 32 url-safe base64-encoded bytes. keeps giving me issues

Viewed 15

I have been getting this error for quite long now. i am trying to decrypt a text content that was encrypted using fernet. the key is passed in through an input element in my django template. after getting the value from the text input, i tried to use it to decrypt the text content but i kept getting this error. Below is my code

my django template code:

<form action="" method="POST" enctype="multipart/form-data">
     {% csrf_token %}
        <h3>Welcome to Encryption, Decryption and Compression program using Python</h3>
         {% for field in form %}
           <div>{{ field }} </div>
                {% endfor  %}
                  <select name="choices" id="choices">
                     <option>Encryption</option>
                     <option>Decryption</option>
                      <option>Encryption and Compression</option>
                      <option>Decryption and Compression</option>
                      <option>Compression</option>
                   </select>
                 <input type="text" name="dkey" id="dkey" placeholder="Enter Decryption Key">
 
                        <button >Proceed</button>
                    </form>

my views.py

def decryption(self, key):
        key = base64.urlsafe_b64encode(bytes(key, encoding="utf-8"))
        f = Fernet(key)

def post(self, request):
        m_file = request.FILES['file']
        opt = request.POST.get('choices')
        if opt == "Decryption":
            dkey = request.POST.get('dkey')
            decrypted = self.decryption(dkey)

the error i get:

ValueError at /
Fernet key must be 32 url-safe base64-encoded bytes.

the fernet key entered through the text input:

**Pl85l36CA7TJe48jv8nWYFD4SWIhIJNFQL8CyyLlXR4=**

Here's the encryption method:

def encryption(self, content):
    key = Fernet.generate_key()
    cipher_suite = Fernet(key)
    cipher_text = cipher_suite.encrypt(bytes(str(content), encoding='utf-8'))
     return cipher_text, key
0 Answers
Related