Python
bcrypt模块是一个用来生成强哈希值的库。本文介绍如何使用bcrypt库对密码进行哈希操作,包括加密、哈希和加盐
介绍
bcrypt是Niels Provos和DavidMazières基于Blowfish密码设计的密码哈希功能,bcrypt 算法通过加盐+哈希生成密码,通过成本因数控制复杂度- 常见加密算法
- 在线 bcrypt 工具
安装
pip install bcrypt使用
生成密码
使用 Python bcrypt 模块生成密码哈希
cat << EOF > gene_bcrypt.py
#!/usr/bin/env python3
import bcrypt
passwd = b'abc'
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(passwd, salt)
print(salt)
print(hashed)
EOF- 示例
$ python3 gene_bcrypt.py
b'$2b$12$H3q7dMVWVHoyVbAq7yyRuu'
b'$2b$12$H3q7dMVWVHoyVbAq7yyRuuskqAGFp4vFVTEtTCv3.9BOb6qlEOou.'
$ python3 gene_bcrypt.py
b'$2b$12$gd2ndHmrx1.8Qlru0Wqwz.'
b'$2b$12$gd2ndHmrx1.8Qlru0Wqwz.G0vA4IcERcN3wv3dFwrehhDnkFx6zMu'说明:不同 盐 生成不同的 哈希值。
检查密码
使用 Python bcrypt 模块验证密码哈希
cat << EOF > check_bcrypt.py
#!/usr/bin/env python3
import bcrypt
passwd = b'abc'
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(passwd, salt)
if bcrypt.checkpw(passwd, hashed):
print("Match!")
else:
print("Not Match!")
EOF- 验证是否匹配
$ python3 check_bcrypt.py
Match!成本因子
Python bcrypt 成本因子
salt = bcrypt.gensalt(rounds=16)通过生成 rounds 控制,上述示例成本因子为 16