0

Below is the code I am trying for Encryption and decryption using Python, on Decryption I am getting the Below Error. Thanks in advance for the help Code:

#!usr/bin/env python
from cryptography.fernet import Fernet
encrypted_message=''
secretkey=''

def encrypt_message(message):
    key=Fernet.generate_key()
    secretkey=key
    encoded_message=message.encode()
    f=Fernet(key)
    encrypted_message=f.encrypt(encoded_message)

    print('encrypted message',encrypted_message)

def decrypt_message(message):
    print("message recieved in decrypt block", message)
    #key=Fernet.generate_key()
    f=Fernet(secretkey)
    return f.decrypt(message)

    print(decrypted_message)

if __name__=="__main__":
    #encrypt_message("#h\"53x8S^U\'yzA")
    print(decrypt_message(encrypt_message("#h\"53x8S^U\'yzA")))

Error:

('encrypted message', 'gAAAAABfX2keyhbp5F2A7vvE67qPiv-UkCfdeXXcDrFzTbtEqtLxFKdV8E0yN5OPrFwXH8-P8Un9U-bCI-2xFAKFKSBv-Y_yfA==')
('message recieved in decrypt block', None)
Traceback (most recent call last):
  File "encrypt.py", line 25, in <module>
    print(decrypt_message(encrypt_message("#h\"53x8S^U\'yzA")))
  File "encrypt.py", line 18, in decrypt_message
    f=Fernet(secretkey)
  File "/usr/lib/python2.7/dist-packages/cryptography/fernet.py", line 37, in __init__
    "Fernet key must be 32 url-safe base64-encoded bytes."
ValueError: Fernet key must be 32 url-safe base64-encoded bytes.
  • There is no `return` statement in `encrypt_message`. In `decrypt_message` `secretkey` is empty (which causes the error), s. [here](https://stackoverflow.com/a/423596). – Topaco Sep 14 '20 at 16:02
  • I added the return statement and was able to enter into the decrypt_message Function. But I am facing the below issue. Traceback (most recent call last): File "encrypt.py", line 26, in decrypt_message(encrypt_message("#h\"53x8S^U\'yzA")) File "encrypt.py", line 19, in decrypt_message f=Fernet(secretkey) File "/usr/lib/python2.7/dist-packages/cryptography/fernet.py", line 37, in __init__ "Fernet key must be 32 url-safe base64-encoded bytes." ValueError: Fernet key must be 32 url-safe base64-encoded bytes. – Suraj Subramanya Sep 14 '20 at 16:44
  • Have you checked the link and set the `global` keyword for `secretkey`? – Topaco Sep 14 '20 at 16:51
  • yes I did and tried, but didn't work for me – Suraj Subramanya Sep 14 '20 at 17:16
  • Hey Bro Thanks It worked. Sorry I had missed few things in it so – Suraj Subramanya Sep 14 '20 at 17:21

0 Answers0