import hmac import random
def hmac_md5(key, s): return hmac.new(key.encode('utf-8'), s.encode('utf-8'), digestmod='MD5').hexdigest()
class User(object): def init(self, username, password): self.username = username self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)]) self.password = hmac_md5(self.key, password)
db = { 'michael': User('michael', '123456'), 'bob': User('bob', 'abc999'), 'alice': User('alice', 'alice2008') }
def login(username, password): user = db[username] return user.password == hmac_md5(user.key, password)
def register(username, password): db[username] = User(username, password)
register('ManiaJack', 'Python') assert login('ManiaJack', 'Python') assert not login('ManiaJack', 'python') assert login('michael', '123456') assert login('bob', 'abc999') assert login('alice', 'alice2008') assert not login('michael', '1234567') assert not login('bob', '123456') assert not login('alice', 'Alice2008') print('ok')
Sign in to make a reply
爱电影的小王纸
-- coding:utf-8 --
import hmac import random
def hmac_md5(key, s): return hmac.new(key.encode('utf-8'), s.encode('utf-8'), digestmod='MD5').hexdigest()
class User(object): def init(self, username, password): self.username = username self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)]) self.password = hmac_md5(self.key, password)
db = { 'michael': User('michael', '123456'), 'bob': User('bob', 'abc999'), 'alice': User('alice', 'alice2008') }
def login(username, password): user = db[username] return user.password == hmac_md5(user.key, password)
def register(username, password): db[username] = User(username, password)
测试:
register('ManiaJack', 'Python') assert login('ManiaJack', 'Python') assert not login('ManiaJack', 'python') assert login('michael', '123456') assert login('bob', 'abc999') assert login('alice', 'alice2008') assert not login('michael', '1234567') assert not login('bob', '123456') assert not login('alice', 'Alice2008') print('ok')