程序的工作原理是用户通过(userinput
和passwordinput
)发送两个输入。将它们与文本文件(即用户名)和上下文(即散列密码)的文件名进行比较。passwordinput
会被散列,如果它返回与散列的原始密码相同的话,"Access Granted"
会被打印出来。如果不匹配,则打印"Wrong Password!1!!"
,如果文件名不存在,则打印"Username not found."
--这个程序只是我在玩hashlib,并试图找到在我的网站上存储密码的方法,我想知道更安全的编写这段代码的方法和漏洞。
import os
import hashlib
username = "coolcat"
password = "my secret password!!"
result = hashlib.sha256(password.encode("utf-8"))
if not os.path.exists(f"{username}.txt"):
open(f"{username}.txt", 'w').close()
with open(f"{username}.txt", "w") as file:
file.write(str(result.digest()))
userinput = input("Your username please : ")
passwordinput = input("Your password please : ")
resulte = hashlib.sha256(passwordinput.encode("utf-8"))
print(str(resulte.digest()))
try :
with open(f"{userinput}.txt", "r") as file:
hashed = file.read()
print(hashed)
if hashed == str(resulte.digest()):
print("Access Granted")
if hashed != str(resulte.digest()):
print("Wrong password!!")
except FileNotFoundError :
print("Username not found!!1!")
发布于 2021-12-23 17:46:47
就目前情况而言,您的代码非常湿(将所有内容写两遍)。hashlib.sha256(variable.encode("utf-8"))
出现两次,str(variable.digest())
出现四次!
使用函数将代码删除(不要重复):
def password_hash(password: str) -> str:
result = hashlib.sha256(password.encode("utf-8"))
return str(result.digest())
如果
考虑这两个背对背的如果声明:
if hashed == str(resulte.digest()):
print("Access Granted")
if hashed != str(resulte.digest()):
print("Wrong password!!")
假设每次调用resulte.digest()
时不返回不同的结果,那么是否有任何方法可以同时获得两个print语句,或者两者都没有?不是的。如果你到了第一个,你就不会到达第二个,反之亦然。在这些情况下使用else
子句:
if hashed == str(resulte.digest()):
print("Access Granted")
else:
print("Wrong password!!")
这段代码是不必要的。
if not os.path.exists(f"{username}.txt"):
open(f"{username}.txt", 'w').close()
如果文件名不存在,它将尝试根据该名称创建一个空文件。如果它确实存在,什么都不会发生。
下一个陈述..。
with open(f"{username}.txt", "w") as file:
..。打开文件,不管是否存在,并将其写入文件。提前创建文件是毫无意义的。
import os
import hashlib
def password_hash(password: str) -> str:
result = hashlib.sha256(password.encode("utf-8"))
return str(result.digest())
username = "coolcat"
password = "my secret password!!"
hashed_password = password_hash(password)
with open(f"{username}.txt", "w") as file:
file.write(hashed_password)
userinput = input("Your username please : ")
passwordinput = input("Your password please : ")
hashed_passwordinput = password_hash(passwordinput)
print(hashed_passwordinput)
try:
with open(f"{userinput}.txt", "r") as file:
hashed = file.read()
print(hashed)
if hashed == hashed_passwordinput:
print("Access Granted")
else:
print("Wrong password!!")
except FileNotFoundError:
print("Username not found!!1!")
此代码将读取进程可访问的任何.txt
文件。如果用户可以上传文件/tmp/uploads/myhash.txt
,那么他们可以将“/tmp/上载/my散列”作为“用户名”,输入对给定结果进行散列的所需文本,并被授予访问权限。
您应该清理用户输入,以确保它只包含有效的用户名字符。
https://codereview.stackexchange.com/questions/272274
复制相似问题