检查密码和用户名输入是否与Python匹配?

时间:2012-06-12 03:01:55

标签: python tkinter username tkinter-entry

我做了一个小程序,应该问你的密码和用户名。输入详细信息后,应检查密码和用户名是否正确。我该如何接近并做到这一点?

from tkinter import *
from getpass import getpass

def callback():
    print(E1)()

top = Tk()
L1 = Label(top, text="User Name")
L1.grid(row=0, column=0)
E1 = Entry(top, bd = 5)
E1.grid(row=0, column=1)

L1 = Label(top, text="Password")
L1.grid(row=1, column=0)
E1 = Entry(top, bd = 5,show="•")
E1.grid(row=1, column=1)

MyButton1 = Button(top, text="Submit", width=10, command=callback)
MyButton1.grid(row=3, column=1)

top.mainloop()

1 个答案:

答案 0 :(得分:1)

这里有一些代码演示了如何使用getpass以及如何根据哈希密码检查用户提供的密码。这忽略了许多问题,例如盐析哈希值,存储身份验证数据的适当位置,需要支持的用户数等等。

import getpass, hashlib

USER = 'ali_baba'
# hashlib.md5('open sesame').hexdigest()
PASSWORD_HASH = '54ef36ec71201fdf9d1423fd26f97f6b'

user = raw_input("Who are you? ")
password = getpass.getpass("What's the password? ")
password_hash = hashlib.md5(password).hexdigest()

if (user == USER) and (password_hash == PASSWORD_HASH):
    print "user authenticated"
else:
    print "user authentication failed"

如果您不想在代码中存储用户名,可以执行以下操作:

# hashlib.md5('ali_baba:open sesame').hexdigest()
AUTH_HASH = '0fce635beba659c6341d76da4f97212f'
user = raw_input("Who are you? ")
password = getpass.getpass("What's the password? ")
auth_hash = hashlib.md5('%s:%s' % (user, password)).hexdigest()
if auth_hash == AUTH_HASH:
    print "user authenticated"
else:
    print "user authentication failed"