将密码+盐存储为哈希值和盐。看看Django是如何做的:基本文档 https://docs.djangoproject.com/en/1.8/topics/auth/passwords/ and source http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py。
在他们存储的数据库中<type of hash>$<salt>$<hash>
在单个字符字段中。您还可以将这三个部分存储在不同的字段中。
设置密码的函数:
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)