目录
加密算法基础
密码学基本概念
# 基本加密术语示例
class CryptoConcepts:
"""
加密基本概念:
- 明文:原始可读数据
- 密文:加密后的数据
- 密钥:用于加密和解密的参数
- 加密:将明文转换为密文的过程
- 解密:将密文转换为明文的过程
"""
def __init__(self):
self.plaintext = "Hello, World!"
self.ciphertext = ""
self.key = "secret_key"加密算法分类
# 加密算法分类
from abc import ABC, abstractmethod
class EncryptionAlgorithm(ABC):
"""加密算法基类"""
@abstractmethod
def encrypt(self, plaintext, key):
pass
@abstractmethod
def decrypt(self, ciphertext, key):
pass
class SymmetricEncryption(EncryptionAlgorithm):
"""对称加密"""
pass
class AsymmetricEncryption(EncryptionAlgorithm):
"""非对称加密"""
pass对称加密算法
AES (高级加密标准)
import os
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
class AESCipher:
"""AES 加密实现"""
def __init__(self, key=None):
# AES-256 需要 32 字节密钥
self.key = key or get_random_bytes(32)
self.block_size = AES.block_size
def encrypt(self, plaintext):
"""加密数据"""
# 生成随机 IV
iv = get_random_bytes(AES.block_size)
# 创建加密器
cipher = AES.new(self.key, AES.MODE_CBC, iv)
# 填充并加密数据
padded_data = pad(plaintext.encode('utf-8'), self.block_size)
ciphertext = cipher.encrypt(padded_data)
# 返回 IV + 密文
return base64.b64encode(iv + ciphertext).decode('utf-8')
def decrypt(self, encrypted_data):
"""解密数据"""
# 解码 base64
raw_data = base64.b64decode(encrypted_data)
# 提取 IV 和密文
iv = raw_data[:self.block_size]
ciphertext = raw_data[self.block_size:]
# 创建解密器
cipher = AES.new(self.key, AES.MODE_CBC, iv)
# 解密并去除填充
decrypted_padded = cipher.decrypt(ciphertext)
decrypted = unpad(decrypted_padded, self.block_size)
return decrypted.decode('utf-8')
# 使用示例
def aes_example():
cipher = AESCipher()
plaintext = "敏感数据需要加密保护"
print(f"原始数据: {plaintext}")
# 加密
encrypted = cipher.encrypt(plaintext)
print(f"加密数据: {encrypted}")
# 解密
decrypted = cipher.decrypt(encrypted)
print(f"解密数据: {decrypted}")
return cipher.key # 保存密钥供后续使用
# AES-GCM 模式(认证加密)
class AESGCMCipher:
"""AES-GCM 认证加密实现"""
def __init__(self, key=None):
self.key = key or get_random_bytes(32)
def encrypt(self, plaintext, associated_data=b""):
"""加密并认证数据"""
# 生成随机 nonce
nonce = get_random_bytes(16)
# 创建 GCM 加密器
cipher = AES.new(self.key, AES.MODE_GCM, nonce=nonce)
# 添加关联数据(不加密但认证)
if associated_data:
cipher.update(associated_data)
# 加密数据
ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode('utf-8'))
# 返回 nonce + tag + ciphertext
result = nonce + tag + ciphertext
return base64.b64encode(result).decode('utf-8')
def decrypt(self, encrypted_data, associated_data=b""):
"""解密并验证数据"""
# 解码 base64
raw_data = base64.b64decode(encrypted_data)
# 提取各部分
nonce = raw_data[:16]
tag = raw_data[16:32]
ciphertext = raw_data[32:]
# 创建 GCM 解密器
cipher = AES.new(self.key, AES.MODE_GCM, nonce=nonce)
# 添加关联数据
if associated_data:
cipher.update(associated_data)
# 解密并验证
try:
decrypted = cipher.decrypt_and_verify(ciphertext, tag)
return decrypted.decode('utf-8')
except ValueError:
raise ValueError("认证失败 - 数据可能被篡改")
# 使用示例
def aes_gcm_example():
cipher = AESGCMCipher()
plaintext = "使用GCM模式的重要数据"
associated_data = b"metadata"
encrypted = cipher.encrypt(plaintext, associated_data)
print(f"GCM加密: {encrypted}")
decrypted = cipher.decrypt(encrypted, associated_data)
print(f"GCM解密: {decrypted}")ChaCha20-Poly1305
from Crypto.Cipher import ChaCha20_Poly1305
class ChaCha20Cipher:
"""ChaCha20-Poly1305 加密实现"""
def __init__(self, key=None):
self.key = key or get_random_bytes(32)
def encrypt(self, plaintext):
"""加密数据"""
# 生成随机 nonce
nonce = get_random_bytes(12)
# 创建加密器
cipher = ChaCha20_Poly1305.new(key=self.key, nonce=nonce)
# 加密数据
ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode('utf-8'))
# 返回 nonce + tag + ciphertext
result = nonce + tag + ciphertext
return base64.b64encode(result).decode('utf-8')
def decrypt(self, encrypted_data):
"""解密数据"""
# 解码 base64
raw_data = base64.b64decode(encrypted_data)
# 提取各部分
nonce = raw_data[:12]
tag = raw_data[12:28]
ciphertext = raw_data[28:]
# 创建解密器
cipher = ChaCha20_Poly1305.new(key=self.key, nonce=nonce)
try:
decrypted = cipher.decrypt_and_verify(ciphertext, tag)
return decrypted.decode('utf-8')
except ValueError:
raise ValueError("认证失败")
def chacha20_example():
cipher = ChaCha20Cipher()
plaintext = "使用ChaCha20加密的数据"
encrypted = cipher.encrypt(plaintext)
print(f"ChaCha20加密: {encrypted}")
decrypted = cipher.decrypt(encrypted)
print(f"ChaCha20解密: {decrypted}")非对称加密算法
RSA 加密算法
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
class RSACipher:
"""RSA 非对称加密实现"""
def __init__(self, key_size=2048):
# 生成 RSA 密钥对
self.key = RSA.generate(key_size)
self.private_key = self.key.export_key()
self.public_key = self.key.publickey().export_key()
def encrypt(self, plaintext, public_key=None):
"""使用公钥加密数据"""
if public_key:
recipient_key = RSA.import_key(public_key)
else:
recipient_key = self.key.publickey()
# 使用 OAEP 填充方案
cipher = PKCS1_OAEP.new(recipient_key)
encrypted = cipher.encrypt(plaintext.encode('utf-8'))
return base64.b64encode(encrypted).decode('utf-8')
def decrypt(self, ciphertext):
"""使用私钥解密数据"""
encrypted_data = base64.b64decode(ciphertext)
cipher = PKCS1_OAEP.new(self.key)
decrypted = cipher.decrypt(encrypted_data)
return decrypted.decode('utf-8')
def sign(self, message):
"""使用私钥对消息签名"""
h = SHA256.new(message.encode('utf-8'))
signature = pkcs1_15.new(self.key).sign(h)
return base64.b64encode(signature).decode('utf-8')
def verify(self, message, signature, public_key=None):
"""使用公钥验证签名"""
if public_key:
verify_key = RSA.import_key(public_key)
else:
verify_key = self.key.publickey()
h = SHA256.new(message.encode('utf-8'))
signature_bytes = base64.b64decode(signature)
try:
pkcs1_15.new(verify_key).verify(h, signature_bytes)
return True
except (ValueError, TypeError):
return False
def rsa_example():
# Alice 生成密钥对
alice = RSACipher()
# Bob 生成密钥对
bob = RSACipher()
# Alice 使用 Bob 的公钥加密消息
message = "这是给Bob的机密消息"
encrypted = alice.encrypt(message, bob.public_key)
print(f"RSA加密: {encrypted}")
# Bob 使用自己的私钥解密
decrypted = bob.decrypt(encrypted)
print(f"RSA解密: {decrypted}")
# 数字签名示例
document = "重要合同内容"
signature = alice.sign(document)
print(f"数字签名: {signature}")
# 验证签名
is_valid = alice.verify(document, signature, alice.public_key)
print(f"签名验证: {is_valid}")ECC (椭圆曲线加密)
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.backends import default_backend
class ECCCipher:
"""ECC 椭圆曲线加密实现"""
def __init__(self, curve=ec.SECP256R1):
# 生成 ECC 密钥对
self.private_key = ec.generate_private_key(curve())
self.public_key = self.private_key.public_key()
def get_public_key_pem(self):
"""获取公钥 PEM 格式"""
return self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
def load_public_key(self, public_key_pem):
"""从 PEM 加载公钥"""
return serialization.load_pem_public_key(
public_key_pem,
backend=default_backend()
)
def derive_shared_key(self, peer_public_key):
"""派生共享密钥"""
shared_secret = self.private_key.exchange(ec.ECDH(), peer_public_key)
# 使用 HKDF 派生加密密钥
derived_key = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b'ecdh key derivation',
backend=default_backend()
).derive(shared_secret)
return derived_key
def sign(self, message):
"""使用 ECDSA 签名"""
signature = self.private_key.sign(
message.encode('utf-8'),
ec.ECDSA(hashes.SHA256())
)
return base64.b64encode(signature).decode('utf-8')
def verify(self, message, signature, public_key=None):
"""验证 ECDSA 签名"""
if public_key is None:
public_key = self.public_key
signature_bytes = base64.b64decode(signature)
try:
public_key.verify(
signature_bytes,
message.encode('utf-8'),
ec.ECDSA(hashes.SHA256())
)
return True
except Exception:
return False
def ecdh_example():
"""ECDH 密钥交换示例"""
# Alice 生成密钥对
alice = ECCCipher()
# Bob 生成密钥对
bob = ECCCipher()
# Alice 派生共享密钥
alice_shared = alice.derive_shared_key(bob.public_key)
# Bob 派生共享密钥
bob_shared = bob.derive_shared_key(alice.public_key)
# 验证共享密钥相同
print(f"ECDH 密钥交换成功: {alice_shared == bob_shared}")
print(f"共享密钥: {base64.b64encode(alice_shared[:16]).decode('utf-8')}...")
# 使用共享密钥进行对称加密
aes_cipher = AESCipher(alice_shared)
message = "使用ECDH派生密钥加密的消息"
encrypted = aes_cipher.encrypt(message)
decrypted = aes_cipher.decrypt(encrypted)
print(f"加密消息: {encrypted}")
print(f"解密消息: {decrypted}")哈希函数
SHA 系列哈希函数
import hashlib
import hmac
class HashFunctions:
"""哈希函数实现"""
@staticmethod
def sha256(data):
"""SHA-256 哈希"""
return hashlib.sha256(data.encode('utf-8')).hexdigest()
@staticmethod
def sha512(data):
"""SHA-512 哈希"""
return hashlib.sha512(data.encode('utf-8')).hexdigest()
@staticmethod
def blake2b(data, key=None):
"""BLAKE2b 哈希(支持密钥)"""
if key:
return hashlib.blake2b(data.encode('utf-8'), key=key.encode('utf-8')).hexdigest()
return hashlib.blake2b(data.encode('utf-8')).hexdigest()
@staticmethod
def hmac_sha256(key, data):
"""HMAC-SHA256"""
return hmac.new(
key.encode('utf-8'),
data.encode('utf-8'),
hashlib.sha256
).hexdigest()
@staticmethod
def pbkdf2_hmac(password, salt, iterations=100000):
"""PBKDF2 密钥派生函数"""
return hashlib.pbkdf2_hmac(
'sha256',
password.encode('utf-8'),
salt.encode('utf-8'),
iterations
).hex()
def hash_examples():
data = "需要哈希的数据"
print("=== 哈希函数示例 ===")
print(f"SHA-256: {HashFunctions.sha256(data)}")
print(f"SHA-512: {HashFunctions.sha512(data)}")
print(f"BLAKE2b: {HashFunctions.blake2b(data)}")
print(f"HMAC-SHA256: {HashFunctions.hmac_sha256('secret', data)}")
# 密码哈希示例
password = "user_password123"
salt = "random_salt"
derived_key = HashFunctions.pbkdf2_hmac(password, salt)
print(f"PBKDF2 派生密钥: {derived_key}")
# 安全密码哈希
from passlib.context import CryptContext
class PasswordHasher:
"""安全密码哈希工具"""
def __init__(self):
# 配置密码哈希上下文
self.pwd_context = CryptContext(
schemes=["bcrypt", "argon2"],
default="bcrypt",
bcrypt__rounds=12
)
def hash_password(self, password):
"""哈希密码"""
return self.pwd_context.hash(password)
def verify_password(self, password, hashed):
"""验证密码"""
return self.pwd_context.verify(password, hashed)
def password_hashing_example():
hasher = PasswordHasher()
password = "my_secure_password"
hashed = hasher.hash_password(password)
print(f"原始密码: {password}")
print(f"哈希密码: {hashed}")
# 验证密码
is_valid = hasher.verify_password(password, hashed)
print(f"密码验证: {is_valid}")
# 错误密码验证
is_valid_wrong = hasher.verify_password("wrong_password", hashed)
print(f"错误密码验证: {is_valid_wrong}")密钥交换协议
Diffie-Hellman 密钥交换
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import dh
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
class DiffieHellman:
"""Diffie-Hellman 密钥交换实现"""
def __init__(self, key_size=2048):
# 生成 DH 参数
self.parameters = dh.generate_parameters(generator=2, key_size=key_size)
# 生成密钥对
self.private_key = self.parameters.generate_private_key()
self.public_key = self.private_key.public_key()
def get_public_key_bytes(self):
"""获取公钥字节"""
return self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
def load_peer_public_key(self, public_key_bytes):
"""加载对端公钥"""
return serialization.load_pem_public_key(
public_key_bytes,
backend=default_backend()
)
def derive_shared_key(self, peer_public_key):
"""派生共享密钥"""
shared_secret = self.private_key.exchange(peer_public_key)
# 使用 HKDF 派生加密密钥
derived_key = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b'dh key derivation',
backend=default_backend()
).derive(shared_secret)
return derived_key
def diffie_hellman_example():
"""Diffie-Hellman 密钥交换示例"""
# Alice 生成 DH 密钥对
alice = DiffieHellman()
# Bob 生成 DH 密钥对
bob = DiffieHellman()
# 交换公钥
alice_public = alice.get_public_key_bytes()
bob_public = bob.get_public_key_bytes()
# 各自派生共享密钥
alice_shared = alice.derive_shared_key(bob.load_peer_public_key(bob_public))
bob_shared = bob.derive_shared_key(alice.load_peer_public_key(alice_public))
print("=== Diffie-Hellman 密钥交换 ===")
print(f"共享密钥匹配: {alice_shared == bob_shared}")
print(f"Alice 共享密钥: {base64.b64encode(alice_shared[:16]).decode('utf-8')}...")
print(f"Bob 共享密钥: {base64.b64encode(bob_shared[:16]).decode('utf-8')}...")
# 现代 TLS 1.3 密钥交换
class TLSKeyExchange:
"""模拟 TLS 1.3 密钥交换"""
def __init__(self):
self.ecdh_cipher = ECCCipher()
def perform_handshake(self, client_hello, server_hello):
"""执行密钥交换握手"""
# 客户端生成临时密钥对
client_ephemeral = ECCCipher()
# 服务器生成临时密钥对
server_ephemeral = ECCCipher()
# 交换公钥并派生主密钥
client_shared = client_ephemeral.derive_shared_key(server_ephemeral.public_key)
server_shared = server_ephemeral.derive_shared_key(client_ephemeral.public_key)
# 派生会话密钥
handshake_secret = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b'tls13 handshake secret',
backend=default_backend()
).derive(client_shared)
return handshake_secret数字签名
数字签名完整实现
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.exceptions import InvalidSignature
import json
import time
class DigitalSignature:
"""数字签名系统"""
def __init__(self):
self.rsa_cipher = RSACipher()
def sign_document(self, document_data):
"""对文档进行数字签名"""
# 创建文档哈希
document_json = json.dumps(document_data, sort_keys=True)
document_hash = hashlib.sha256(document_json.encode('utf-8')).digest()
# 使用私钥签名
signature = self.rsa_cipher.sign(document_json)
# 创建签名文档
signed_document = {
'document': document_data,
'signature': signature,
'public_key': self.rsa_cipher.public_key.decode('utf-8'),
'timestamp': time.time(),
'algorithm': 'RSA-SHA256'
}
return signed_document
def verify_document(self, signed_document):
"""验证文档签名"""
try:
# 提取文档和签名
document_data = signed_document['document']
signature = signed_document['signature']
public_key_pem = signed_document['public_key']
# 重新计算文档哈希
document_json = json.dumps(document_data, sort_keys=True)
# 验证签名
is_valid = self.rsa_cipher.verify(
document_json,
signature,
public_key_pem.encode('utf-8')
)
return is_valid
except Exception as e:
print(f"签名验证错误: {e}")
return False
def digital_signature_example():
"""数字签名示例"""
signer = DigitalSignature()
# 创建重要文档
contract = {
"parties": ["Alice", "Bob"],
"amount": 10000,
"currency": "USD",
"date": "2024-01-15",
"terms": "Payment due in 30 days"
}
# 对文档签名
signed_contract = signer.sign_document(contract)
print("=== 数字签名示例 ===")
print(f"签名文档: {json.dumps(signed_contract, indent=2)}")
# 验证签名
is_valid = signer.verify_document(signed_contract)
print(f"签名验证结果: {is_valid}")
# 尝试篡改文档
tampered_contract = signed_contract.copy()
tampered_contract['document']['amount'] = 20000 # 修改金额
is_valid_tampered = signer.verify_document(tampered_contract)
print(f"篡改后验证结果: {is_valid_tampered}")
# 证书和 PKI 系统
class SimplePKI:
"""简化 PKI 系统"""
def __init__(self):
self.ca_private_key = RSA.generate(2048)
self.ca_public_key = self.ca_private_key.publickey()
self.certificates = {}
def issue_certificate(self, subject_name, public_key):
"""颁发数字证书"""
certificate_data = {
'version': '1.0',
'serial_number': len(self.certificates) + 1,
'subject': subject_name,
'public_key': public_key,
'issuer': 'Simple CA',
'valid_from': time.time(),
'valid_to': time.time() + 365*24*60*60, # 1年有效期
'signature_algorithm': 'SHA256-RSA'
}
# 对证书数据进行签名
certificate_json = json.dumps(certificate_data, sort_keys=True)
h = SHA256.new(certificate_json.encode('utf-8'))
signature = pkcs1_15.new(self.ca_private_key).sign(h)
certificate_data['signature'] = base64.b64encode(signature).decode('utf-8')
self.certificates[subject_name] = certificate_data
return certificate_data
def verify_certificate(self, certificate):
"""验证证书有效性"""
try:
# 提取签名
signature = certificate.pop('signature')
signature_bytes = base64.b64decode(signature)
# 重新计算哈希
certificate_json = json.dumps(certificate, sort_keys=True)
h = SHA256.new(certificate_json.encode('utf-8'))
# 使用 CA 公钥验证签名
pkcs1_15.new(self.ca_public_key).verify(h, signature_bytes)
# 检查证书有效期
current_time = time.time()
if current_time < certificate['valid_from'] or current_time > certificate['valid_to']:
return False
return True
except (ValueError, TypeError):
return False
finally:
# 恢复签名字段
certificate['signature'] = signature实际应用场景
安全通信协议
class SecureMessaging:
"""安全消息传递系统"""
def __init__(self, user_id):
self.user_id = user_id
self.rsa_cipher = RSACipher()
self.session_keys = {}
def establish_session(self, peer_id, peer_public_key):
"""建立安全会话"""
# 生成会话密钥
session_key = get_random_bytes(32)
# 使用对方公钥加密会话密钥
encrypted_session_key = self.rsa_cipher.encrypt(
base64.b64encode(session_key).decode('utf-8'),
peer_public_key
)
# 存储会话密钥
self.session_keys[peer_id] = session_key
return {
'from': self.user_id,
'encrypted_session_key': encrypted_session_key,
'public_key': self.rsa_cipher.public_key.decode('utf-8')
}
def send_message(self, peer_id, message):
"""发送加密消息"""
if peer_id not in self.session_keys:
raise ValueError("未建立安全会话")
session_key = self.session_keys[peer_id]
aes_cipher = AESCipher(session_key)
encrypted_message = aes_cipher.encrypt(message)
return {
'from': self.user_id,
'to': peer_id,
'encrypted_message': encrypted_message,
'timestamp': time.time()
}
def receive_message(self, encrypted_package, sender_public_key=None):
"""接收并解密消息"""
session_key = self.session_keys.get(encrypted_package['from'])
if not session_key:
raise ValueError("未知发送者或会话密钥不存在")
aes_cipher = AESCipher(session_key)
decrypted_message = aes_cipher.decrypt(encrypted_package['encrypted_message'])
return decrypted_message
def secure_messaging_example():
"""安全消息传递示例"""
# 创建两个用户
alice = SecureMessaging("alice")
bob = SecureMessaging("bob")
print("=== 安全消息传递 ===")
# Alice 与 Bob 建立安全会话
handshake = alice.establish_session("bob", bob.rsa_cipher.public_key.decode('utf-8'))
print(f"会话建立握手: {handshake}")
# Bob 处理握手(在实际系统中需要实现)
bob.session_keys["alice"] = base64.b64decode(
bob.rsa_cipher.decrypt(handshake['encrypted_session_key'])
)
# Alice 发送加密消息
message = "这是机密消息内容"
encrypted_package = alice.send_message("bob", message)
print(f"加密消息包: {encrypted_package}")
# Bob 解密消息
decrypted_message = bob.receive_message(encrypted_package)
print(f"解密消息: {decrypted_message}")
# 文件加密系统
class FileEncryptionSystem:
"""文件加密系统"""
def __init__(self, master_password):
# 从主密码派生加密密钥
self.master_key = hashlib.pbkdf2_hmac(
'sha256',
master_password.encode('utf-8'),
b'file_encryption_salt',
100000
)
def encrypt_file(self, file_path, output_path=None):
"""加密文件"""
if not output_path:
output_path = file_path + '.encrypted'
# 读取文件内容
with open(file_path, 'rb') as f:
file_data = f.read()
# 生成文件特定的密钥
file_salt = get_random_bytes(16)
file_key = hashlib.pbkdf2_hmac(
'sha256',
self.master_key,
file_salt,
1
)
# 加密文件数据
iv = get_random_bytes(16)
cipher = AES.new(file_key, AES.MODE_CBC, iv)
padded_data = pad(file_data, AES.block_size)
encrypted_data = cipher.encrypt(padded_data)
# 保存加密文件(盐 + IV + 加密数据)
with open(output_path, 'wb') as f:
f.write(file_salt + iv + encrypted_data)
return output_path
def decrypt_file(self, encrypted_file_path, output_path=None):
"""解密文件"""
if not output_path:
output_path = encrypted_file_path.replace('.encrypted', '.decrypted')
# 读取加密文件
with open(encrypted_file_path, 'rb') as f:
encrypted_data = f.read()
# 提取盐、IV 和加密数据
file_salt = encrypted_data[:16]
iv = encrypted_data[16:32]
ciphertext = encrypted_data[32:]
# 重新派生文件密钥
file_key = hashlib.pbkdf2_hmac(
'sha256',
self.master_key,
file_salt,
1
)
# 解密文件数据
cipher = AES.new(file_key, AES.MODE_CBC, iv)
decrypted_padded = cipher.decrypt(ciphertext)
decrypted_data = unpad(decrypted_padded, AES.block_size)
# 保存解密文件
with open(output_path, 'wb') as f:
f.write(decrypted_data)
return output_path安全最佳实践
加密配置和参数选择
class SecurityBestPractices:
"""安全最佳实践配置"""
@staticmethod
def get_secure_aes_config():
"""获取安全的 AES 配置"""
return {
'key_size': 32, # AES-256
'mode': 'GCM', # 认证加密模式
'key_derivation': 'PBKDF2',
'pbkdf2_iterations': 100000
}
@staticmethod
def get_secure_rsa_config():
"""获取安全的 RSA 配置"""
return {
'key_size': 3072, # 3072 位密钥
'padding': 'OAEP', # 最优非对称加密填充
'hash_algorithm': 'SHA-256'
}
@staticmethod
def get_secure_ecc_config():
"""获取安全的 ECC 配置"""
return {
'curve': 'P-256', # secp256r1
'key_derivation': 'HKDF-SHA256'
}
@staticmethod
def validate_crypto_parameters(algorithm, parameters):
"""验证加密参数安全性"""
security_standards = {
'AES': {
'min_key_size': 16, # AES-128
'recommended_key_size': 32, # AES-256
'secure_modes': ['GCM', 'CCM', 'EAX']
},
'RSA': {
'min_key_size': 2048,
'recommended_key_size': 3072,
'secure_padding': ['OAEP', 'PSS']
},
'ECC': {
'secure_curves': ['P-256', 'P-384', 'P-521']
}
}
if algorithm not in security_standards:
raise ValueError(f"不支持的算法: {algorithm}")
standard = security_standards[algorithm]
if 'key_size' in parameters:
if parameters['key_size'] < standard['min_key_size']:
raise ValueError(f"{algorithm} 密钥大小不安全")
return True
# 完整的加密工具类
class CryptoUtils:
"""加密工具类"""
@staticmethod
def generate_secure_random(length=32):
"""生成安全随机数"""
return get_random_bytes(length)
@staticmethod
def secure_compare(a, b):
"""安全比较(防止时序攻击)"""
return hmac.compare_digest(a, b)
@staticmethod
def cleanup_sensitive_data(data):
"""清理敏感数据"""
# 对于字节数据,用零覆盖
if isinstance(data, bytes):
return b'\x00' * len(data)
# 对于字符串,用空字符串覆盖
elif isinstance(data, str):
return ''
else:
return None
@staticmethod
def get_algorithm_recommendations():
"""获取算法推荐"""
return {
'symmetric_encryption': {
'recommended': 'AES-256-GCM',
'alternative': 'ChaCha20-Poly1305',
'key_derivation': 'PBKDF2-SHA256 (100,000 iterations)'
},
'asymmetric_encryption': {
'recommended': 'RSA-3072-OAEP',
'alternative': 'ECC P-256',
'signature': 'RSA-PSS or ECDSA'
},
'hashing': {
'recommended': 'SHA-256',
'password_hashing': 'Argon2 or bcrypt'
},
'key_exchange': {
'recommended': 'ECDH with P-256',
'alternative': 'RSA key exchange'
}
}
def main():
"""主函数 - 运行所有示例"""
print("开始运行加密算法示例...\n")
# AES 示例
aes_example()
print()
# AES-GCM 示例
aes_gcm_example()
print()
# ChaCha20 示例
chacha20_example()
print()
# RSA 示例
rsa_example()
print()
# ECDH 示例
ecdh_example()
print()
# 哈希函数示例
hash_examples()
print()
# 密码哈希示例
password_hashing_example()
print()
# Diffie-Hellman 示例
diffie_hellman_example()
print()
# 数字签名示例
digital_signature_example()
print()
# 安全消息传递示例
secure_messaging_example()
print()
# 显示安全推荐
recommendations = CryptoUtils.get_algorithm_recommendations()
print("=== 安全算法推荐 ===")
print(json.dumps(recommendations, indent=2))
if __name__ == "__main__":
# 安装所需库
# pip install pycryptodome cryptography passlib
main()安装依赖
在运行代码前,请安装必要的 Python 库:
pip install pycryptodome cryptography passlib