密码的Python3 os.uradom()

2024-06-08 04:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用os.urandom()生成一个密码salt。 然后使用以下内容创建哈希:

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

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

感谢您的帮助:)


Tags: csv字符串密码字节ospasswordhmacurandom
1条回答
网友
1楼 · 发布于 2024-06-08 04:49:11

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

相关问题 更多 >

    热门问题