问题
通常,登录某个网站或 APP,用户名和密码需要使用。密码加密后如何存储?请使用它 Python 加密密码。 阅读资料:
- 存储和存储用户密码 Python 示例
- Hashing Strings with Python
- Python’s safest method to store and retrieve passwords from a database
import secretsfrom hmac import HMACfrom hashlib import sha256def 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 + resultdef 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 中的
bytes
和str
类型,可参考 bytes和str类型在Python3中 secret
模块参考资料 Generate secure random numbers for managing secrets