0

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
Zubairu
  • 1
  • 1
  • Show your Encryption method. – NKSM Sep 16 '22 at 17:42
  • Sorry, I misunderstood the problem (of course 32 bytes will base-64 encode to 44, and you are asking for the already-encoded version). Instead, look closely at `decrypted = self.decryption(dkey)`. What do you expect will be the resulting value of `decrypted`? Did you check that? (Hint: does it say `return` anywhere in the `decryption` method?) Please read [ask] and https://ericlippert.com/2014/03/05/how-to-debug-small-programs/, and look for problems before posting. Also, welcome to Stack Overflow. – Karl Knechtel Sep 16 '22 at 17:57
  • @Zubairu, You have to use the same key for decryption. Generated `key=Fernet.generate_key()` at encryption should be used for decryption: `fernet = Fernet(generated_key_at_encryption)` > `fernet.decrypt(base64.b64decode(key))`. – NKSM Sep 16 '22 at 18:00

0 Answers0