Python是从数据库中存储和检索密码的最安全的方法 [英] Python's safest method to store and retrieve passwords from a database

查看:175
本文介绍了Python是从数据库中存储和检索密码的最安全的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望在数据库中存储用户名和密码,并且想知道最安全的方法是什么。我知道我必须在某处使用盐,但不知道如何安全地生成它,或者如何应用它来加密密码。一些示例Python代码将不胜感激。谢谢。

Looking to store usernames and passwords in a database, and am wondering what the safest way to do so is. I know I have to use a salt somewhere, but am not sure how to generate it securely or how to apply it to encrypt the password. Some sample Python code would be greatly appreciated. Thanks.

推荐答案

存储密码+盐作为散列和盐。看看Django如何做:基本文档
在数据库中,它们在单个字段中存储< hash类型&$ $< salt> $< hash> 。您也可以将这三个部分存储在单独的字段中。

Store the password+salt as a hash and the salt. Take a look at how Django does it: basic docs and source. In the db they store <type of hash>$<salt>$<hash> in a single char field. You can also store the three parts in separate fields.

设置密码的功能:

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()

The get_hexdigest is just a thin wrapper around some hashing algorithms. You can use hashlib for that. Something like 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)

这篇关于Python是从数据库中存储和检索密码的最安全的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆