我是编程新手,想知道这是否可行。我正在尝试创建一个受密码保护的脚本,其中输入密码一次,然后需要在下次打开脚本时继续执行该脚本。我将密码存储在文件中并对其进行加密,然后在下次打开脚本时检查该文件是否存在。我遇到的问题是检查密码是否匹配,因为原始密码在函数中作为局部变量。
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = encrypt(pw, 10) #encodes the string with a key in a seperate encrypt function
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
#I can not check pwCheck == pw since pw is a local var.
#progression of script here
else:
createFile()
我知道将局部变量设置为全局变量被认为是不好的。有没有办法重组我迄今为止所拥有的一切来使这项工作发挥作用?当我写这篇文章时,我想我可能已经想出了一个可能的解决方案,但我现在没有时间测试它。我是否使用 pwCheck 的相同 key 运行相同的加密函数,然后检查它是否 == 到 PW.txt 的第一行?这是正确的和/或还有其他解决方案吗?
谢谢。
使用 Windows、Python 3.4
最佳答案
也许可以使用单向哈希来代替“加密”。然后,您可以对随后输入的密码进行哈希处理,并将其与文件中存储的哈希进行检查...类似:
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = sha.new(pw).digest
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
previous = open('PW.txt', 'r')
prevPass = previous.read()
hashed = sha.new(pwCheck).digest()
if (hashed==prevPass):
#progression of script here
else:
createFile()
关于python - Python 局部变量与全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532746/