.py 文件中的哈希密码
Hashing Password in .py file
我在标题中是怎么说的,我希望在保存密码时对其进行哈希处理。用这个可以吗?
def __OnClickSaveLoginButton(self):
id = self.idEditLine.GetText()
pwd = self.pwdEditLine.GetText()
if (len(id) == 0 or len(pwd) == 0):
self.PopupNotifyMessage("ID and Password required",self.SetIDEditLineFocus)
return
file_object = open("account.cfg", "w")
file_object.write(id+"\n"+pwd)
self.PopupNotifyMessage("Saved.",self.SetIDEditLineFocus)
file_object.close()
您需要使用 python hashlib。示例可能如下所示:
import hashlib
def valid_password(userid, password):
user = get_user(userid)
pw_hash = hashlib.sha256(password).hexdigest()
if user.hash == pw_hash:
return True
return False
我还建议您查看此 SO
中提到的一些密码存储最佳实践
编辑:我在此示例中使用了 sh256,但它作为消息摘要更有用。更好的用法是 hashlib.pbkdf2_hmac
或其他密钥派生函数。有写的好here.
如果您要在 Python 中散列密码,如 nudies 所述,hashlib.pbkdf2_hmac 是正确的。
如果您想将结果保存在 Base64 中,这是一个合理的选择,因为它会将其转换为字符串。
请记住,您还必须存储盐值和迭代次数;选择尽可能多的迭代次数 CPU 可以承受。
不要请求比本机哈希函数可以支持的更多字节的输出;例如,PBKDF2-HMAC-SHA-512 密码散列的上限为 64 字节;其他的少了。
我在 my github repository 有一个完整的示例,包括所有正常 SHA 变体的测试向量,其核心部分是
import argparse,hashlib,base64,timeit
BinaryOutput = hashlib.pbkdf2_hmac('sha512',args.password, args.salt, args.iterations, args.outputBytes)
BinaryOutput.encode('base64')
我在标题中是怎么说的,我希望在保存密码时对其进行哈希处理。用这个可以吗?
def __OnClickSaveLoginButton(self):
id = self.idEditLine.GetText()
pwd = self.pwdEditLine.GetText()
if (len(id) == 0 or len(pwd) == 0):
self.PopupNotifyMessage("ID and Password required",self.SetIDEditLineFocus)
return
file_object = open("account.cfg", "w")
file_object.write(id+"\n"+pwd)
self.PopupNotifyMessage("Saved.",self.SetIDEditLineFocus)
file_object.close()
您需要使用 python hashlib。示例可能如下所示:
import hashlib
def valid_password(userid, password):
user = get_user(userid)
pw_hash = hashlib.sha256(password).hexdigest()
if user.hash == pw_hash:
return True
return False
我还建议您查看此 SO
中提到的一些密码存储最佳实践编辑:我在此示例中使用了 sh256,但它作为消息摘要更有用。更好的用法是 hashlib.pbkdf2_hmac
或其他密钥派生函数。有写的好here.
如果您要在 Python 中散列密码,如 nudies 所述,hashlib.pbkdf2_hmac 是正确的。
如果您想将结果保存在 Base64 中,这是一个合理的选择,因为它会将其转换为字符串。
请记住,您还必须存储盐值和迭代次数;选择尽可能多的迭代次数 CPU 可以承受。
不要请求比本机哈希函数可以支持的更多字节的输出;例如,PBKDF2-HMAC-SHA-512 密码散列的上限为 64 字节;其他的少了。
我在 my github repository 有一个完整的示例,包括所有正常 SHA 变体的测试向量,其核心部分是
import argparse,hashlib,base64,timeit
BinaryOutput = hashlib.pbkdf2_hmac('sha512',args.password, args.salt, args.iterations, args.outputBytes)
BinaryOutput.encode('base64')