Python 密码学基础:hashlib、hmac、secrets、cryptography 实战
Introduction
密码学是安全开发的基础。本文讲解 Python 标准库 hashlib、hmac、secrets 的用法,以及 cryptography 库实现 AES 对称加密、RSA 非对称加密、数字签名的完整示例。
---
哈希(不可逆)
import hashlib
# MD5(仅用于文件校验,不用于安全目的)
md5 = hashlib.md5(b'hello').hexdigest()
# SHA-256(推荐)
sha256 = hashlib.sha256(b'hello').hexdigest()
# 文件哈希
def file_hash(filepath):
h = hashlib.sha256()
with open(filepath, 'rb') as f:
while chunk := f.read(8192):
h.update(chunk)
return h.hexdigest()
HMAC(消息认证)
import hmac, hashlib
secret = b'secret_key'
message = b'{"action": "login", "user_id": 1}'
mac = hmac.new(secret, message, hashlib.sha256).hexdigest()
print(f"HMAC: {mac}")
# 验证
def verify(mac, message, key):
return hmac.compare_digest(mac, hmac.new(key, message, hashlib.sha256).hexdigest())
secrets(安全随机数)
import secrets
# 生成安全随机数
token = secrets.token_urlsafe(32) # 43字符的 URL 安全令牌
password = secrets.token_hex(16) # 32字符十六进制密码
print(token, password)
# 随机选择
items = ['a', 'b', 'c', 'd']
choice = secrets.choice(items)
print(choice)
cryptography 库(AES/RSA)
pip install cryptography
from cryptography.fernet import Fernet
# 对称加密(Fernet = AES + HMAC)
key = Fernet.generate_key()
cipher = Fernet(key)
token = cipher.encrypt(b'机密内容')
plain = cipher.decrypt(token)
print(plain.decode())
常见问题
Q1: 密码存数据库用什么?bcrypt 或 argon2,慢哈希函数抗暴力破解。不要用 MD5/SHA1 存密码。
Q2: AES-128 和 AES-256 选哪个?都行,AES 本身无已知弱点。AES-256 密钥空间更大,更抗未来量子计算攻击。
Q3: JWT 安全吗?JWT 本身是标准,但要注意:签名算法用 RS256(不用 HS256 共享密钥),过期时间要设,敏感信息不要放 payload(base64 可解码)。
延伸阅读
- TLS/SSL 原理
- OWASP 安全编码规范
- Python 渗透测试基础
---
作者:小马 | 绍大技术网 shaoda.net