Created
December 21, 2011 14:29
-
-
Save flying19880517/1506222 to your computer and use it in GitHub Desktop.
加入了随机 Salt 的哈希算法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os,binascii | |
from hashlib import sha256 | |
from hmac import HMAC | |
def encrypt_password(password, salt=None): | |
"""Hash password on the fly. | |
先通过标准随机库生成 64 bits 的随机 salt, | |
使用了标准的 SHA-256 做为基本的 hash 算法, | |
使用标准 HMAC 算法作为 salt 混淆。 | |
并且进行了 10 次混淆 hash。 | |
最后将 salt 和 hash 结果一起返回。 | |
""" | |
if salt is None: | |
salt = os.urandom(8) # 64 bits. | |
assert 8 == len(salt) | |
assert isinstance(salt, bytes) | |
if isinstance(password, str): | |
password=password.encode() | |
assert isinstance(password, bytes) | |
result = password | |
for i in range(10): | |
result = HMAC(result, salt, sha256).digest() | |
return {'hashed':result, 'salt':salt} | |
def validate_password(input_password, salt, hashed): | |
return hashed == encrypt_password(input_password, salt)['hashed'] | |
if __name__=='__main__': | |
password='secret password' | |
result = encrypt_password(password) | |
salt=binascii.hexlify(result['salt']).decode("ascii") | |
hashed=binascii.hexlify(result['hashed']).decode('ascii') | |
print(salt, hashed) | |
assert validate_password(password, bytes.fromhex(salt), bytes.fromhex(hashed)) | |
#assert validate_password(password, binascii.unhexlify(salt.encode('ascii')), binascii.unhexlify(hashed.encode('ascii'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment