写点什么

架构师训练营第十一周”安全稳定“作业

用户头像
随秋
关注
发布于: 2021 年 02 月 07 日

Q: 请用你熟悉的编程语言写一个用户密码验证函数,Boolean checkPW(String 用户 ID,String 密码明文,String 密码密文),返回密码是否正确 boolean 值,密码加密算法使用你认为合适的加密算法。


A:

采用 md5 加密,加密时加盐(user_id)

# -*- encoding:utf-8 -*-from __future__ import absolute_import
import hashlibimport uuid

class MD5PasswordHasher:
@classmethod def ensure_bytes(cls, value, errors='strict'): if not value: return b'' if isinstance(value, str): return value.encode('utf-8', errors) return value
@classmethod def encode(cls, salt, raw_password): return hashlib.md5(cls.ensure_bytes(salt + raw_password)).hexdigest()
@classmethod def check_pw(cls, salt, raw_password, password): return password == cls.encode(salt, raw_password)

def task(): user_id = str(uuid.uuid1()) raw_password = '123456' print("user_id:", user_id, "raw_password:", raw_password)
password = MD5PasswordHasher.encode(user_id, raw_password) print("encode password:", password)
is_right = MD5PasswordHasher.check_pw(user_id, raw_password, password) print("Check user_id:{}, raw_password:{}, password:{}, is_right:{}".format(user_id, raw_password, password, is_right))

if __name__ == '__main__': task()
# user_id: a2b457ce-694f-11eb-a0d1-acde48001122 raw_password: 123456# encode password: 4097426d8590940611f1d80b1fe6e719# Check user_id:a2b457ce-694f-11eb-a0d1-acde48001122, raw_password:123456, password:4097426d8590940611f1d80b1fe6e719, is_right:True
复制代码


用户头像

随秋

关注

还未添加个人签名 2018.04.27 加入

还未添加个人简介

评论

发布
暂无评论
架构师训练营第十一周”安全稳定“作业