与往常一样,使用源:
# root/django/trunk/django/contrib/auth/models.py
# snip
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = smart_str(raw_password), smart_str(salt)
if algorithm == 'crypt':
try:
import crypt
except ImportError:
raise ValueError('"crypt" password algorithm not supported in this environment')
return crypt.crypt(raw_password, salt)
if algorithm == 'md5':
return md5_constructor(salt + raw_password).hexdigest()
elif algorithm == 'sha1':
return sha_constructor(salt + raw_password).hexdigest()
raise ValueError("Got unkNown password algorithm type in password.")
如我们所见,密码摘要是通过使用选定的哈希算法将盐和密码连接起来而制成的。然后,将算法名称,原始盐和密码哈希进行合并,并用“ $”分隔以构成摘要。
# Also from root/django/trunk/django/contrib/auth/models.py
def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return hsh == get_hexdigest(algo, salt, raw_password)
为了验证密码,django只是验证相同的盐和相同的密码是否导致相同的摘要。