23.1 引言
随着应用程序处理的数据越来越敏感(密码、隐私、支付信息等),安全性变得尤为重要。
本章将学习 Python 中常用的安全技术:
- 哈希算法(不可逆)
- 加盐存储密码
- 对称加密与非对称加密
- 基础用户认证实现
- 安全编程注意事项
23.2 哈希(Hash)
23.2.1 基本哈希算法
示例:
import hashlib
data = "my_secret_password".encode()
sha256_hash = hashlib.sha256(data).hexdigest()
md5_hash = hashlib.md5(data).hexdigest()
print("SHA256:", sha256_hash)
print("MD5:", md5_hash)
哈希算法是不可逆的,常用于完整性校验、密码存储。
23.2.2 加盐哈希(Salt)
示例:
import os, hashlib
salt = os.urandom(16) # 16字节随机盐
password = "mypassword".encode()
hash_value = hashlib.pbkdf2_hmac(
'sha256', password, salt, 100000
)
print("Salt:", salt.hex())
print("Hash:", hash_value.hex())
加盐能有效防止彩虹表攻击与暴力破解。
23.3 对称加密(Fernet)
安装:
pip install cryptography
示例:
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
cipher = Fernet(key)
# 加密
token = cipher.encrypt(b"secret message")
print("加密后:", token)
# 解密
plain = cipher.decrypt(token)
print("解密后:", plain.decode())
对称加密使用同一个密钥加解密,适用于本地数据保护。
23.4 非对称加密(RSA)
示例:
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
# 生成密钥对
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
# 加密
message = b"secret"
ciphertext = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# 解密
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print("原文:", plaintext.decode())
非对称加密使用公钥加密、私钥解密,常用于安全网络通信。
23.5 简单用户认证系统
示例:
import hashlib, os
users = {}
def register(username, password):
salt = os.urandom(16)
hash_pwd = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
users[username] = (salt, hash_pwd)
def login(username, password):
if username not in users:
return False
salt, stored_hash = users[username]
test_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
return test_hash == stored_hash
# 使用
register("alice", "mypassword")
print(login("alice", "mypassword")) # True
print(login("alice", "wrongpass")) # False
使用加盐+哈希存储密码,避免明文存储,提升安全性。
23.6 安全编程注意事项
- 不要明文存储密码,必须用哈希+盐
- 敏感数据传输必须使用 HTTPS/SSL
- 不要硬编码密钥,使用环境变量或配置文件管理
- 控制第三方库依赖,定期更新
- 严格验证用户输入,防止注入攻击(SQL/命令注入等)
23.7 小结
技术 | 作用 |
hashlib | 哈希算法,保护密码完整性 |
pbkdf2_hmac | 加盐哈希,防止暴力破解和彩虹表攻击 |
Fernet | 对称加密,用于本地数据保护 |
RSA | 非对称加密,用于安全数据传输 |
用户认证逻辑 | 安全存储密码、身份验证 |
掌握本章后,你就能为 Python 应用加入基础安全机制,防止数据泄露与账号被盗。