i’m new to django and I’ve wondered how the authentication system and hashed passwords worked in django? And why is it not possible to know the users password? (Even if i know the algorithm and the salt)
In my mind, i see the authentication some what like a python condition: If input == password: authenticated =True (Obviously i know it isn’t coded like that)
But I can’t figure out how it is hashed and unhashed, and if there is a way to know what the user password is?
Its not possible to know a user's password because they're encrypted.
Django uses any one of a number of cryptographically secure hash algorithms to do this. Cryptographic hash algorithms are written to take data of any length and return a number (the "message digest") that seems completely random, but has several special properties:
How exactly you write cryptographic hash algorithms to do that is complicated, but worth reading more into if you're interested.
What Django does is essentially this:
def is_password_correct(hash, salt, rounds, password):
"""<hash>, <salt>, and <rounds> come from the DB
<password> comes from the user
"""
digest = hash_function(salt + password)
# make guessing a password take lots more work
for n in range(rounds):
digest = hash_function(digest)
if digest == hash:
return True
else:
return False
Where hash_function()
is one of the cryptographic hash functions Django supports (such as BCrypt, or PBKDF2).
This is much more secure than storing a user's password in a database in plain text, because if a hacker were to get a copy of the database all they would get is the password hashes. Recovering passwords from password hashes requires guessing the actual password and checking it by running the above function. This protects your users who may have (counter to all security recommendations) used the same password in multiple places.
The price you pay for this security is having to run the hash algorithm every time a user logs in to "re-encrypt" their password and check if it matches what's in the database (which can take several milliseconds per login attempt).
You can read more about their password system here