盐和散列蟒蛇密码 [英] Salt and hash a password in python
问题描述
这code被认为哈希与盐的密码。盐和哈希密码被保存在数据库中。密码本身是没有的。
由于操作的敏感性,我想,以确保一切都洁净。
请注意:我用b64en code的网址安全版本是出于习惯。
进口hashlib
进口的base64
进口UUID密码='test_password
盐= base64.urlsafe_b64en code(uuid.uuid4()。字节)
t_sha = hashlib.sha512()
t_sha.update(密码+盐)
hashed_password = base64.urlsafe_b64en code(t_sha.digest())
编辑:这个答案是错的。不要使用加密哈希存储密码。使用密码哈希。
由我看起来很好。不过,我pretty确保你实际上并不需要的base64。你可能只是这样做:
进口hashlib,UUID
盐= uuid.uuid4()。十六进制
hashed_password = hashlib.sha512(密码+盐).hexdigest()
如果它不产生困难,可以通过存储的原始字节而不是十六进制字符串盐和哈希密码让你的数据库稍微更高效的存储。要做到这一点,将十六进制
与字节
和 hexdigest
与消化
。
This code is supposed to hash a password with a salt. The salt and hashed password are being saved in the database. The password itself is not.
Given the sensitive nature of the operation, I wanted to make sure everything was kosher.
Note: I use the url safe version of b64encode out of habit.
import hashlib
import base64
import uuid
password = 'test_password'
salt = base64.urlsafe_b64encode(uuid.uuid4().bytes)
t_sha = hashlib.sha512()
t_sha.update(password+salt)
hashed_password = base64.urlsafe_b64encode(t_sha.digest())
EDIT: This answer is wrong. Don't use a cryptographic hash to store passwords. Use a password hash.
Looks fine by me. However, I'm pretty sure you don't actually need base64. You could just do this:
import hashlib, uuid
salt = uuid.uuid4().hex
hashed_password = hashlib.sha512(password + salt).hexdigest()
If it doesn't create difficulties, you can get slightly more efficient storage in your database by storing the salt and hashed password as raw bytes rather than hex strings. To do so, replace hex
with bytes
and hexdigest
with digest
.
这篇关于盐和散列蟒蛇密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!