how could I get the password hash in Django ORM?

1.7k Views Asked by At

I want to get the user by a password so when I type the following code

User.objects.get(password='test') 

I get an error and I already know what is error is talking about which occurs because the password has been hashed but I want to get it, so what is the trick I need here?

1

There are 1 best solutions below

2
On BEST ANSWER

I get an error and I already know what is error is talking about which occurs because the password has been hashed but I want to get it, so what is the trick I need here?

You don't. The hash algorithm makes use of a random value (named the salt [wiki]) that is stored together with the hashed password. This thus means that for a given password, there is not a single hash, but an infinite number. For a fixed salt size, the number of hash results is, strictly speaking, finite, but still the number of hashes is that large that it is infeasible to generate/test all.

Salt is used to prevent against a set of pre-comuted hashes (also known as rainbow table [wiki]). By making use of salt, it is almost impossible to compute the hash for every possible salt for a given set of passwords, and it thus makes the problem of reversing the hashes to passwords harder.

You thus should iterate over the User objects, and use the .check_password(…) method [Django-doc]:

for user in User.objects.all():
    if user.check_password('test'):
        # … we found a user with password 'test'
        pass

For more information, see the How Django stores passwords section of the documentation.