0

I'm trying to decrypt a string using fernet. My code (assume files already exist with pre-filled data):

import hashlib
import bcrypt
from cryptography.fernet import Fernet
import base64

#encrypting
############################################################
file = open('message.txt', 'r+')
message = file.read()
file.close()
password = input("Enter password: ")
file = open('passsalt.txt', 'r+')
salt = file.read()
file.close()
passwordnhash = str(password) + str(salt)
passwordnhash = passwordnhash.encode('utf-8')
hash = hashlib.sha256(passwordnhash).digest()
key = base64.urlsafe_b64encode(hash)
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
file = open('message.ivf', 'w+')
file.write(str(encMessage))
file.close()
############################################################
#decrypting
file = open('message.ivf', 'r+')
token = file.read()
file.close()
token = token.encode('utf-8')
file = open('passsalt.txt', 'r+')
salt = file.read()
file.close()
passwordnhash = str(password) + str(salt)
passwordnhash = passwordnhash.encode('utf-8')
hash = hashlib.sha256(passwordnhash).digest()
key = base64.urlsafe_b64encode(hash)
fernet = Fernet(key)



#token = fernet.encrypt(message)
d = fernet.decrypt(token)
print(d)

This returns the error

cryptography.fernet.InvalidToken

While decrypting. I'm unsure on what to do. I have viewed many questions but none have a fix for me. Links:

Stack Overflow question 1

Stack Overflow question 2

Stack Overflow question 3

Thanks in advance

Thomas
  • 1,214
  • 4
  • 18
  • 45
  • The problem is with the string you are decrypting. – BokiX Mar 31 '22 at 12:21
  • 1
    Try `file.write(encMessage.decode('utf8'))` instead of `file.write(str(encMessage))`. Besides, you should use a professional key derivation (like PBKDF2) and a random salt. – Topaco Mar 31 '22 at 12:49
  • @Topaco do you mean that fernet us insecure then? PBKDF2 is hashing (I'm pretty sure) and this needs to be reversible sooo. Im already using hashlib and sha256 to hash in my program – Thomas Mar 31 '22 at 17:10
  • I never claimed that Fernet is insecure, only pointed out that your key derivation could be more secure. Don't apply a home-made one, but an algorithm developed by professionals like e.g. PBKDF2, and use a randomly generated salt and not a static one. – Topaco Mar 31 '22 at 17:40

0 Answers0