Discuss / Python / 作业2

作业2

Topic source

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

import hashlib, random

class User(object):

    def __init__(self,username,password):

        self.username = username

        self.salt = ''.join([chr(random.randint(48,122)) for i in range(20)])

        self.password = get_md5(self.username, password + self.salt)

def register(username, password):

    user = User(username,password)

    db[username] = user

def get_md5(name:str, pws:str)->str:

    md5 = hashlib.md5()

    md5.update((pws+name).encode('utf-8'))

    return md5.hexdigest()

def login(username:str, password:str)->bool:

    user = db[username]

    return user.password == get_md5(username,password+user.salt)

db = {

    'michael': User('michael', '123456'),

    'bob': User('bob', 'abc999'),

    'alice': User('alice', 'alice2008')

}

# 测试:

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