【问题标题】:Python3 os.urandom() for password salts用于密码盐的 Python3 os.urandom()
【发布时间】:2021-08-24 22:52:23
【问题描述】:

我想用os.urandom() 生成密码盐。 然后创建一个哈希:

hashed_pw = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 300000)

这很好用,但我还想在退出程序后存储哈希和盐以登录。 我目前使用 csv 文件存储密码/盐。 如果我现在使用csv.DictReader 读取用户名的数据,则盐的类型为str。 如果现在比较哈希它不起作用,因为哈希算法需要一个字节。 如果我使用salt.encode(),它现在是一个字节,但与原始字节不同。 我怎样才能解决这个问题? 如果我只是生成一个随机字符串并保存到 csv 中,然后在散列函数中对两者进行编码,我只会让它工作。 但我认为使用os.urandom 作为盐更安全。

任何帮助表示赞赏:)

【问题讨论】:

  • 您没有一个简单的程序来存储/检索 csv,所以我们需要做一些猜测,但是您可以在编写 csv 时对 salt 进行 bin2ascii 编码,在读取时反之.
  • 另外,最好明确编码。 passwrod.encode() 假定您的默认编码始终相同。 password.encode(encoding="utf-8") 解决了这个问题。
  • @tdelaney 仅供参考,在 Python 3.2 之后,encoding 默认为 utf-8,但显式优于隐式 :)

标签: python csv passwords salt


【解决方案1】:

bytes 对象上使用.hex() 以获得适合CSV 的str 值,并在该str 上使用.fromhex() 以再次获得bytes

import os
import hashlib

password = "mysecurepassword"
salt = os.urandom(10) # returns bytes
hashed_pw = hashlib.pbkdf2_hmac('sha256','password'.encode(),salt,300000)
hexpw = hashed_pw.hex()
hexsalt = salt.hex()
print(hexpw,hexsalt) # suitable for CSV

pw2 = bytes.fromhex(hexpw)
salt2 = bytes.fromhex(hexsalt)

assert(hashed_pw == pw2)
assert(salt == salt2)

输出:

e6134156ba833d22c30d4e387103505727232f74905b3a3119bd4b6d121cbff4 97181907f5f1a5b61d8c

【讨论】:

  • 谢谢!效果很好
猜你喜欢
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 2015-02-10
  • 2012-07-04
  • 2014-10-31
  • 1970-01-01
相关资源
最近更新 更多