0

I use bcrypt in another API and it works for me there, I copied the code over to my django app and I am getting the error:

TypeError: Strings must be encoded before checking

What type of field should my password field be set to in my database model? Currently it is models.CharField

password = models.CharField(max_length=200, default=None)

To set the password in the database I am doing:

passW = self.context['request'].data["password"]
encodedPass = passW.encode('utf8')
instance.userprofile.password = bcrypt.hashpw(encodedPass, bcrypt.gensalt(rounds=14))
instance.userprofile.save()

To check the password when they enter it in frontend I am doing:

passW = self.context['request'].data["password"]
encodedPass = passW.encode('utf8')
print(f"raw password {passW}")
print(f"encoded pass {encodedPass}")
print(f"stored pass {instance.userprofile.password}")
# Checks if the supplied passcode matches the user's login passcode
if bcrypt.checkpw(encodedPass, instance.userprofile.password):
     return instance

encodedPass returns b'omitted' and the stored pass returns b'omitted'

FYI I am using Firebase integrated with Django rest framework for authentication, we are using phone auth with a texted one time passcode. but as an extra layer of security I have a password stored in the database, which is checked upon login. I have looked at Django docs on hashing passwords in the database, but my app is not built in the way this is for. I have a route in my django app for checking the hashed password with bcrypt, not sure why this is not working.

kbessemer
  • 125
  • 1
  • 10
  • Have you tried `bcrypt.checkpw(encodedPass, instance.userprofile.password.encode('utf8'))` ? – JPG Dec 12 '22 at 18:45
  • That turns the stored pass in db to this: b"b'omitted'" – kbessemer Dec 12 '22 at 18:56
  • hmm. [This might help you](https://stackoverflow.com/questions/33907663/how-to-use-bcrypt-to-encrypt-passwords-in-django) – JPG Dec 12 '22 at 19:01

1 Answers1

0

The problem is using models.CharField() for the hashed password field in your database.

You must use models.BinaryField()

kbessemer
  • 125
  • 1
  • 10