python 练习0021

问题

通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。
阅读资料:

  • 用户密码的存储与 Python 示例
  • Hashing Strings with Python
  • Python’s safest method to store and retrieve passwords from a database

代码

import secrets
from hmac import HMAC
from hashlib import sha256

def encrypt_password(password, salt=None):
    if salt == None:
        # secrets.token_hex(n) 注释:
        # Return a random text string, in hexadecimal. The string has nbytes random bytes, 
        # each byte converted to two hex digits
        # 生成随机 32 bytes salt(256 bits),其实生成了64 bytes(512 bits)? (没搞清楚..
        salt = secrets.token_hex(32)
        # print(type(salt))

    if isinstance(salt, str):
        # print('salt is unicode', salt, ' ', len(salt))
        salt = salt.encode('utf-8')

    if isinstance(password, str):
        # print('password is unicode ', password)
        password = password.encode('utf-8')

    result = password
    for i in range(10):
        # digest 生成字符串摘要,hexdigest 生成 16 进制摘要
        result = HMAC(result, salt, sha256).hexdigest().encode('utf-8')

    return salt + result

def validate_password(hashed, password):
    return hashed == encrypt_password(password, hashed[:64])

if __name__ == '__main__':
    password = 'this is password'
    print('='*50)
    hashed_password = encrypt_password(password)
    print('hashed_password is ', hashed_password)
    print('='*50)
    if validate_password(hashed_password, password):
        print('ecrypt successfully!')
    else:
        print('no no no')

注释

  • 关于 Python3 中的bytesstr 类型,可以参考 Python3中的bytes和str类型
  • secret 模块参考资料 Generate secure random numbers for managing secrets

你可能感兴趣的:(Python,练习册,每天一个小程序)