将密码+盐存储为哈希和盐。看一下Django的工作方式:基本文档和源代码。它们在数据库中存储<type of hash>$<salt>$<hash>
在单个char字段中。您也可以将这三个部分存储在单独的字段中。
设置密码的功能:
def set_password(self, raw_password):
import random
algo = 'sha1'
salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
hsh = get_hexdigest(algo, salt, raw_password)
self.password = '%s$%s$%s' % (algo, salt, hsh)
get_hexdigest只是一些哈希算法的瘦包装。您可以为此使用hashlib。就像是hashlib.sha1('%s%s' % (salt, hash)).hexdigest()
并检查密码的功能:
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)