如何使用Django在数据库上存储哈希密码?

时间:2014-08-02 04:18:42

标签: django hash passwords

我想在输入密码时让文本框输入加星号,我也希望密码作为哈希密码保存在数据库中。

视图

class UserCreate(CreateView):
    model = ModelUser
    fields = ['first_name', 'password', 'username', 'dob', 'email', 'unit', 'house', 'road', 'suburb', 'state', 'postcode', 'country', 'id_type', 'id_no']

URL配置

url(r'^add_user/$', views.UserCreate.as_view()),

模型

class ModelUser(AbstractUser):
    client_id = models.IntegerField(null=True)  #id_client in voipswitch database
    user_type = models.CharField(max_length=15, default='client')
    dob = models.DateField(blank=True, null=True)
    phone = models.CharField(max_length=20, default=0)
    unit = models.CharField(max_length=20, blank=True, null=True)
    house = models.CharField(max_length=20, blank=True, null=True)
    road = models.CharField(max_length=25, blank=True, null=True)
    suburb = models.CharField(max_length=25, blank=True, null=True)
    state = models.CharField(max_length=25, blank=True, null=True)
    postcode = models.CharField(max_length=15, blank=True, null=True)
    country = models.CharField(max_length=30, blank=True, null=True)
    id_type = models.CharField(max_length=25, blank=True, null=True)
    id_no = models.CharField(max_length=30, blank=True, null=True)
    reg_time = models.DateTimeField(editable=False, default=datetime.datetime.today())

    def __unicode__(self):
        return self.phone

1 个答案:

答案 0 :(得分:1)

因此,使用CharField作为密码

password = models.CharField(max_length=255, blank=True)

允许您在表单中使用PasswordInput,使用户界面为“明星”。

password = forms.PasswordInput()

然后在密码下将密码哈希存储到数据库中,您需要确保它是字符串,而不是字节。其他人提到的Django的internal hashers默认会返回字符串。如果您使用scrypt之类的东西(我假设是Python3),请务必在将其存储到数据库之前对其进行解码:

import scrypt, os, base64

def generate_password(length=255):
    chars = string.ascii_letters + string.digits
    return ''.join(choice(chars) for _ in range(length))

user.password = base64.b64encode(scrypt.encrypt(
    generate_password(datalength), user.password
))
user.save()

后来验证它......

try:
    scrypt.decrypt(base64.b64decode(user.password), 'guessed_password')
    return True
except scrypt.error:
    return False

注意 - 我遇到的scrypt编码问题会被跟踪here