我是编程新手,想知道这是否可行。我正在尝试创建一个受密码保护的脚本,在该脚本中输入一次密码,然后在下次打开脚本时需要执行该脚本。我在一个文件中存储和加密密码,然后在下次打开脚本时检查该文件是否存在。我遇到的问题是检查密码是否匹配,因为原始密码在函数中作为局部变量。
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()
我知道将局部变量设为全局变量被认为是不好的。有没有办法重组我目前拥有的东西来完成这项工作?在我写这篇文章时,我想我可能已经想出了一个可能的解决方案,但我现在没有时间测试它。我是否使用相同的 key 为 pwCheck 运行相同的加密函数,然后检查它是否 == 到 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()
