Python密码学基础
密码学安全学习路径 | 模块1 | 课程3
1. 引言
密码学是信息安全的基础,而Python是实现密码学算法的理想语言。本课程将介绍Python密码学编程的基础知识,包括常见的加密技术、哈希函数、密钥管理等内容。
学习目标: 掌握使用Python实现基本密码学操作的方法,了解常见密码学库的使用,能够编写简单的加密解密程序。
2. 基本概念
2.1 密码学简介
密码学是关于信息安全的科学,主要研究如何在不安全的环境中保护信息:
- 加密与解密:将明文转换为密文,以及从密文恢复明文
- 完整性验证:确保信息在传输过程中未被篡改
- 身份认证:验证通信双方的身份
- 不可否认性:防止发送方否认曾发送过信息
2.2 Python密码学库
Python提供了多个密码学库,其中最常用的包括:
# 安装相关库
pip install cryptography
pip install pycryptodome
pip install pyOpenSSL
pip install hashlib # 包含在Python标准库中
# 基本导入示例
import hashlib
from cryptography.fernet import Fernet
from Crypto.Cipher import AES
3. 对称加密
3.1 Fernet(对称加密)
Fernet是一种简单易用的对称加密系统:
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
print(f"密钥: {key}")
# 创建加密器
cipher = Fernet(key)
# 加密
message = "Hello, Cryptography!".encode()
encrypted = cipher.encrypt(message)
print(f"加密后: {encrypted}")
# 解密
decrypted = cipher.decrypt(encrypted)
print(f"解密后: {decrypted.decode()}")
3.2 AES加密
AES是目前最流行的对称加密算法之一:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
# 生成密钥和初始向量
key = get_random_bytes(16) # AES-128需要16字节密钥
iv = get_random_bytes(16) # 初始向量
# 创建加密器
cipher = AES.new(key, AES.MODE_CBC, iv)
# 加密(需要对数据进行填充)
message = b"Secret message that needs to be encrypted"
padded_message = pad(message, AES.block_size)
ciphertext = cipher.encrypt(padded_message)
# 解密
decipher = AES.new(key, AES.MODE_CBC, iv)
decrypted = unpad(decipher.decrypt(ciphertext), AES.block_size)
print(f"解密后: {decrypted.decode()}")
注意: 在实际应用中,密钥和初始向量的安全存储和传输至关重要,不应硬编码在代码中。
4. 非对称加密
4.1 RSA加密
RSA是最广泛使用的非对称加密算法:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 生成RSA密钥对
key = RSA.generate(2048)
private_key = key
public_key = key.publickey()
# 导出密钥
private_pem = private_key.export_key().decode()
public_pem = public_key.export_key().decode()
print(f"私钥: {private_pem[:100]}...")
print(f"公钥: {public_pem[:100]}...")
# 使用公钥加密
message = b"This is a secret message for RSA encryption"
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(message)
# 使用私钥解密
decipher = PKCS1_OAEP.new(private_key)
decrypted = decipher.decrypt(ciphertext)
print(f"解密后: {decrypted.decode()}")
4.2 数字签名
使用私钥创建数字签名,使用公钥验证签名:
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
# 生成密钥对
key = RSA.generate(2048)
private_key = key
public_key = key.publickey()
# 原始消息
message = b"Message that needs to be signed"
# 计算消息哈希
h = SHA256.new(message)
# 使用私钥签名
signature = pkcs1_15.new(private_key).sign(h)
print(f"签名: {signature.hex()[:50]}...")
# 使用公钥验证签名
try:
pkcs1_15.new(public_key).verify(h, signature)
print("签名验证成功!")
except (ValueError, TypeError):
print("签名验证失败!")
5. 哈希函数
5.1 SHA系列
Python的hashlib模块提供了多种哈希算法:
import hashlib
# 待哈希的消息
message = b"Hello, Cryptography!"
# SHA-256
sha256_hash = hashlib.sha256(message).hexdigest()
print(f"SHA-256: {sha256_hash}")
# SHA-512
sha512_hash = hashlib.sha512(message).hexdigest()
print(f"SHA-512: {sha512_hash}")
# MD5(不推荐用于安全场景)
md5_hash = hashlib.md5(message).hexdigest()
print(f"MD5: {md5_hash}")
5.2 HMAC
使用HMAC进行消息认证:
import hmac
import hashlib
# 密钥和消息
key = b"secret_key"
message = b"Message to authenticate"
# 创建HMAC对象
h = hmac.new(key, message, hashlib.sha256)
digest = h.hexdigest()
print(f"HMAC: {digest}")
# 验证HMAC
def verify_hmac(key, message, received_digest):
h = hmac.new(key, message, hashlib.sha256)
calculated_digest = h.hexdigest()
return hmac.compare_digest(calculated_digest, received_digest)
# 模拟验证
is_valid = verify_hmac(key, message, digest)
print(f"HMAC验证: {'成功' if is_valid else '失败'}")