Discuss / Python / 作业

作业

Topic source

桂兴牛2号

#1 Created at ... [Delete] [Delete and Lock User]

第一题 import hashlib db={'michael':'e10adc3949ba59abbe56e057f20f883e','bob': '878ef96e86145580c38c87f0410ad153','alice': '99b1c2188db85afee403b1536010c2c9'}

def login(user,password): if user in db.keys(): md5=hashlib.md5() md5.update(password.encode('utf-8')) if db[user]==md5.hexdigest(): return True else: return False 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')

第二题 import random import hashlib

#定义获取MD5码的方法

def get_md5(s): return hashlib.md5(s.encode('utf-8')).hexdigest()

#创建User类,并赋予username,password,salt的属性 class User(object): def init(self,username,password): self.username=username self.salt=''.join([chr(random.randint(48, 122)) for i in range(20)])

    #User的password属性为password+salt的md5码
    self.password=get_md5(password+self.salt)

#创建User类的数据库 db={'michael': User('michael', '123456'),'bob': User('bob', 'abc999'),'alice': User('alice', 'alice2008')}

def login(username,password):

#michael=User('michael','123456')
if username in db.keys():
    user=db[username]
    return user.password == get_md5(password+user.salt)

测试:

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


  • 1

Reply