在 Python 中加盐并散列密码 [英] Salt and hash a password in Python

查看:32
本文介绍了在 Python 中加盐并散列密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码应该使用盐来散列密码.盐和散列密码被保存在数据库中.密码本身不是.

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.

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

推荐答案

这个答案是错误的.SHA512 的单次迭代,这使得它不适合用作密码散列函数.请改用此处的其他答案之一.

This answer is wrong. A single iteration of SHA512 is fast, which makes it inappropriate for use as a password hashing function. Use one of the other answers here instead.

我觉得不错.但是,我很确定您实际上并不需要 base64.你可以这样做:

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

如果它不会造成困难,您可以通过将 salt 和散列密码存储为原始字节而不是十六进制字符串来稍微提高数据库中的存储效率.为此,请将 hex 替换为 bytes,将 hexdigest 替换为 digest.

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.

这篇关于在 Python 中加盐并散列密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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