Discuss / Python / hashlib 转载

hashlib 转载

# -*-coding: utf-8 -*-import hashlibdef calc_md5(password):    md5 = hashlib.md5()  # 调用md5方法    md5.update(password.encode('utf-8'))  # 对password进行更新    return md5.hexdigest()  # 计算返回def login(user, password):    for k, v in db.items():  # 循环db中数据        if k == user:  # 匹配user            if calc_md5(password) == v:  # 匹配password                return True            else:                return Falsedb = {    'michael': 'e10adc3949ba59abbe56eo57f20f883e',    'bob': '878ef96e86145580c38c87f0410ad153',    'alice': '99b1c2188db85afee403b1536010c2c9'}# 测试:assert login('michael', '123456')assert login('bob', 'abc999')assert login('alice', 'alice2008')assert not login('michael', '1234567')assert not login('bob', 'abc9999')assert not login('alice', 'alice20088')print('ok')



第二题

# -*-coding: utf-8 -*-import hashlib, random

db = {}

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

class User(object):
    def __init__(self, username, password):
        self.username = username
        self.salt = ''.join ([chr(random.randint(478, 122) for i in range(20))])
        self.password = get_md5(password + str(self.salt))

db = {
    'michael': 'e10adc3949ba59abbe56eo57f20f883e',    'bob': '878ef96e86145580c38c87f0410ad153',    'alice': '99b1c2188db85afee403b1536010c2c9'}

def login(username, password):
    user = db[username]
    return user.password == get_md5(password + str(self.salt))

# 测试:assert login('michael', '123456')
assert login('bob', 'abc999')
assert login('alice', 'alice2008')
assert not login('michael', '1234567')
assert not login('bob', 'abc9999')
assert not login('alice', 'alice20088')

print('ok')



  • 1

Reply