ens*_*are 31 python encryption passwords password-protection
希望将用户名和密码存储在数据库中,并且想知道最安全的方法是什么.我知道我必须在某处使用盐,但我不确定如何安全地生成它或如何应用它来加密密码.一些示例Python代码将不胜感激.谢谢.
rz.*_*rz. 38
将密码+ salt存储为哈希和salt.看看Django是如何做到的:基本文档和源代码.在db中,它们存储 <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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
Ter*_*way 13
我在这里回答:https://stackoverflow.com/a/18488878/1661689,@ Koffie也是如此.
我不知道如何强调所接受的答案是不安全的.它比纯文本更好,并且比无保留的哈希更好,但它仍然极易受到字典甚至暴力攻击.相反,请使用像bcrypt这样的慢速KDF(或者至少使用10000次迭代的PBKDF2)
| 归档时间: |
|
| 查看次数: |
48883 次 |
| 最近记录: |