局部变量与全局变量 Python



我是编程新手,想知道这是否可能。 我正在尝试创建一个受密码保护的脚本,其中输入一次密码,然后在下次打开脚本时需要继续执行脚本。 我正在文件中存储和加密密码,然后在下次打开脚本时检查该文件是否存在。 我遇到的问题是检查密码是否匹配,因为原始密码在函数中作为局部变量。

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 的相同密钥运行相同的加密函数,然后检查它是否是 == 到 PW.txt 的第一行? 这是否正确和/或是否有其他解决方案?

谢谢。

使用 Windows,Python 3.4

而不是"加密",也许使用 1 路哈希。然后,您可以对随后输入的密码进行哈希处理,并将其与文件中存储的哈希值进行对比......像这样:

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()

我真的希望这只是一个练习,因为如果您关心安全性,您应该使用其他身份验证机制来门禁访问。最明显的是 unix 权限和 sudo 来控制访问。

假设它只是一个练习,只需有一个函数来检查输入与文件。像这样:

def doAuth():
    isAuthed = getPassInput() == getPassFromFile()
    if isAuthed:
       return True
    else:
       raise HellNoException("Passwords differ")

最新更新