Search code examples
pythonbcrypt

How to compare hashed password to Input() in Python?


Goal:

Currently learning how to encrypt passwords using Python.

Current code:

import bcrypt

passwd = b'False'

salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(passwd, salt)

x = input()

print(hashed == bcrypt.hashpw(x, hashed))

Problem:

I might be doing this wrong, need a bit of guidance how to achieve this correctly.

How can I insert a input value between the apostrophes forb''? That's where the password will be and compared to the Hashed one.

This is what I have tried (Also, Im I on the right lines?):

x = b'%s' % (input())

Output on CMD

    x = b'%s' % (input())
TypeError: %b requires a bytes-like object, or an object that implements __bytes__, not 'str'

Goal

I am trying to compare input to the hashed password.


Solution

  • You should understand what b'' does before using it, and that would allow you to look for a solution in the right direction.

    The answer is: it indicates that what you're assigning is a string bytes literal. That basically means that you have a bunch of bytes as your data. (See these answers)

    Once you know that you can search how to convert a string to bytes in Python, which leads you here

    So, the answer to your initial question (and yes, you should use checkpw), is:

    print(hashed == bcrypt.hashpw(x.encode('utf-8'), hashed))