用户注册,将“用户名”,“密码”,“盐值”存入用户表
输入:密码明文
输出:密码密文+盐值
import hashlib, random, string def get_salt(length=8): ''' 从a-zA-Z0-9生成指定数量的随机字符 :param length:字符数量 :return: ''' salt = ''.join(random.sample(string.ascii_letters + string.digits, length)) return salt def hash_salt(pwd): ''' 获取盐和密码密文 :param pwd: 密码明文 :return: ''' salt = get_salt() # 盐值 pwd_salt = pwd + salt # 加盐后的密码 md5_pwd_salt = hashlib.md5(pwd_salt.encode()).hexdigest() return salt, md5_pwd_salt def auth(username, pwd): """ 认证用户名密码是否匹配 :param username: :param pwd: :return: """ # 根据username在用户表中查询出salt, pwd密文 salt = "WTAkEeRJ" md5_pwd_salt = 'a4545264e99c2baee850a9fec92f5b45' # 根据pwd明文和salt算出密文 pwd_salt = pwd + salt # 加盐后的密码 md5_str = hashlib.md5(pwd_salt.encode()).hexdigest() # 将算出的密文和用户表中存放的密文进行对比 return md5_pwd_salt == md5_str if __name__ == '__main__': print(hash_salt("pwd1234567")) print(auth("username", "pwd1234567"))