Jacobian
Jacobian

Reputation: 10802

How to use make_password and check_password manually?

I try to use make_password and check_password functions manually. I do it like this in one of my views (just for testing reasons):

#iteration one:
def enter(request):
    res = make_password('admin')
    return HttpResponse(res)

So, when I go to enter page, I see this stuff:

pbkdf2_sha256$15000$fmX24ZPCKBdA$fvpfYMacxOi44QFDeLLfRRUN85RweMJTfxxoC+YS2XE=

Let's suppose that I store this output in a text file (again for testing reasons) passwords.txt in a form:

1    pbkdf2_sha256$15000$fmX24ZPCKBdA$fvpfYMacxOi44QFDeLLfRRUN85RweMJTfxxoC+YS2XE= 
2    ....hash for another user   

On the second iteration I want to check my password (let it be stored in GET['pass'] in request variable), but do not know how:

def login(request):
    # How to use check_password here to check against data stored in
    # passwords.txt
    # it should either output False
    # or an id, like 1 in our test case for password 'admin'.

And I want to stress it again, that I want to use it manually, just in order to understand the logic behind these functions. So, I do not want to let Django do it for me at this moment.

Upvotes: 5

Views: 7170

Answers (1)

You need to use the django.contrib.auth.hashers.check_password, and pass it both the unencrypted password and the encrypted string, and it returns True if they match, False if not.

Thus

encrypted = 'pbkdf2_sha256$15000$fmX24...'

if check_password(request.POST['pass'], encrypted):
    print("Login successful")

Note that you don't ever want to submit passwords using GET method, because with GET the passwords will be stored in logs and browser history and whatever indefinitely.

Upvotes: 9

Related Questions