python 练习0021

时间:2019-04-18
本文章向大家介绍python 练习0021,主要包括python 练习0021使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

问题

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

代码

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 位? (没搞清楚..
        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')

注释