登录密码验证,利用MD5编码存储密码法
#登陆密码验证,MD5编码存储密码法(加盐和username,其实也可以生成一个随机数,这样更难猜测)
import hashlib
class User(object):
def __init__(self,username,passward):
self.username=username
self.passward=register(username,passward)
#调用get_md5(),返回加username和盐的MD5码
def register(username,password):
return get_md5(password+username+'the-Salt')
#返回MD5码
def get_md5(s):
md5=hashlib.md5()
md5.update(s.encode('utf-8'))
return md5.hexdigest()
#存储已有的username和password
db={'Bob':User('Bob','123'),'Lily':User('Lily','456')}
#登录
def login(username,password):
#为了抛出username不存在的错误
try:
loginer=register(username,password)
user=db[username]
#登录成功
if loginer==user.passward:
print("Login succeeded")
#失败
else:
print("Password or Username error")
except:
print("user does not exist")
username=input("please write your name:")
password=input("please write your password:")
login(username,password)
hmac版
#登陆密码验证,MD5编码存储密码法(加盐和username,也可以生成一个随机数,这样更难猜测)
import hashlib,hmac
class User(object):
def __init__(self,username,passward):
self.username=username
self.passward=register(username,passward)
def register(username,password):
#new()中的参数得是bytes格式
username=username.encode('utf-8')
password=password.encode('utf-8')
h=hmac.new(username,password,digestmod='MD5')
return h.hexdigest()
db={'Bob':User('Bob','123'),'Lily':User('Lily','456')}
#登录
def login(username,password):
#为了抛出username不存在的错误
try:
loginer=register(username,password)
user=db[username]
#登录成功
if loginer==user.passward:
print("Login succeeded")
#失败
else:
print("Password or Username error")
except:
print("user does not exist")
username=input("please write your name:")
password=input("please write your password:")
login(username,password)