python密码处理(可用于生产模式)
2015-10-13 10:46
260 查看
import os from hashlib import sha256 from hmac import HMAC def encrypt_password(password, salt=None): """Hash password on the fly.""" if salt is None: salt = os.urandom(8) # 64 bits. assert 8 == len(salt) assert isinstance(salt, str) if isinstance(password, unicode): password = password.encode('UTF-8') assert isinstance(password, str) result = password for i in xrange(10): result = HMAC(result, salt, sha256).digest() return salt + result
这里先随机生成 64 bits 的 salt,再选择 SHA-256 算法使用 HMAC 对密码和 salt 进行 10 次叠代混淆,最后将 salt 和 hash 结果一起返回。
使用的方法很简单:
hashed = encrypt_password('secret password')
下面是验证函数,它直接使用 encrypt_password 来对密码进行相同的单向转换并比较
def validate_password(hashed, input_password): return hashed == encrypt_password(input_password, salt=hashed[:8]) assert validate_password(hashed, 'secret password')
测试密码代码项目s21
相关文章推荐
- Python文件读写
- 俄罗斯方块pygame
- python通过接口上传图片造测试数据
- python之函数用法__str__()
- python 安装pymssql
- python 使用datetime模块timedelta实现日期时间相加
- python datetime模块用strftime 格式化时间
- python的程序格式要求
- Python 基础语法(四)
- Python 基础语法(三)
- python:IndentationError:expected an indented block错误解决
- python2.7 numpy scipy
- python tab键自动补齐命令
- 一键获取隐藏Wi-Fi SSID:利用Python和Scapy发现隐藏无线热点
- 在windows7(64位)下安装python(3.4)的theano库
- Python 数据库 sqlite3模块
- 详解Python中的元组与逻辑运算符
- Python中的字典与成员运算符初步探究
- 举例讲解Python中的身份运算符的使用方法
- Python的条件语句与运算符优先级详解