密码学实战:从古典密码到现代加密算法 密码学基础 核心概念 机密性(Confidentiality):只有授权方可以读取 完整性(Integrity):数据未被篡改 认证性(Authentication):验证身份 不可抵赖性(Non-repudiation):发送方无法否认 古典密码 凯撒密码(Caesar Cipher) 原理:字母表移位 维吉尼亚密码(Vigenère Cipher) 原理:使用关键词进行多表替换 对称加密 AES(Advanced Encryption Standard) 特点: 分组密码:128 位分组 密钥长度:128/192/256 位 安全、高效、广泛应用 Python 实现: 加密模式 ECB 模式(不推荐) 独立加密每个分组 相同明文产生相同密文 不安全
机密性(Confidentiality):只有授权方可以读取
完整性(Integrity):数据未被篡改
认证性(Authentication):验证身份
不可抵赖性(Non-repudiation):发送方无法否认
原理:字母表移位
def caesar_cipher(text, shift): result = "" for char in text: if char.isalpha(): shift_amount = shift % 26 if char.islower(): result += chr((ord(char) - ord('a') + shift_amount) % 26 + ord('a')) else: result += chr((ord(char) - ord('A') + shift_amount) % 26 + ord('A')) else: result += char return result # 示例 plaintext = "HELLO WORLD" ciphertext = caesar_cipher(plaintext, 3) print(ciphertext) # KHOOR ZRUOG
原理:使用关键词进行多表替换
def vigenere_cipher(text, key, mode='encrypt'): result = "" key_repeated = (key * (len(text) // len(key) + 1))[:len(text)] for i, char in enumerate(text): if char.isalpha(): key_char = key_repeated[i] shift = ord(key_char.upper()) - ord('A') if mode == 'decrypt': shift = -shift if char.islower(): result += chr((ord(char) - ord('a') + shift) % 26 + ord('a')) else: result += chr((ord(char) - ord('A') + shift) % 26 + ord('A')) else: result += char return result # 示例 plaintext = "ATTACKATDAWN" key = "LEMON" ciphertext = vigenere_cipher(plaintext, key, 'encrypt') print(ciphertext) # LXFOPVEFRNHR
特点:
Python 实现:
from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes # 加密 def aes_encrypt(plaintext, key): iv = get_random_bytes(16) # 初始化向量 cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(plaintext.encode(), 16)) return iv + ciphertext # 解密 def aes_decrypt(ciphertext, key): iv = ciphertext[:16] cipher = AES.new(key, AES.MODE_CBC, iv) plaintext = unpad(cipher.decrypt(ciphertext[16:]), 16) return plaintext.decode() # 使用示例 key = get_random_bytes(32) # AES-256 plaintext = "This is a secret message" ciphertext = aes_encrypt(plaintext, key) decrypted = aes_decrypt(ciphertext, key) print(f"加密: {ciphertext.hex()}") print(f"解密: {decrypted}")
from Crypto.Cipher import AES # GCM 模式 def aes_gcm_encrypt(plaintext, key, aad=None): cipher = AES.new(key, AES.MODE_GCM) cipher.update(aad) if aad else None ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode()) return cipher.nonce, ciphertext, tag def aes_gcm_decrypt(nonce, ciphertext, tag, key, aad=None): cipher = AES.new(key, AES.MODE_GCM, nonce=nonce) cipher.update(aad) if aad else None plaintext = cipher.decrypt_and_verify(ciphertext, tag) return plaintext.decode()
原理:基于大整数分解困难问题
密钥生成:
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP # 生成密钥对 key = RSA.generate(2048) private_key = key.export_key() public_key = key.publickey().export_key() # 保存密钥 with open('private.pem', 'wb') as f: f.write(private_key) with open('public.pem', 'wb') as f: f.write(public_key)
加密解密:
# 加密(使用公钥) def rsa_encrypt(plaintext, public_key): key = RSA.import_key(public_key) cipher = PKCS1_OAEP.new(key) ciphertext = cipher.encrypt(plaintext.encode()) return ciphertext # 解密(使用私钥) def rsa_decrypt(ciphertext, private_key): key = RSA.import_key(private_key) cipher = PKCS1_OAEP.new(key) plaintext = cipher.decrypt(ciphertext) return plaintext.decode()
数字签名:
from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 # 签名(使用私钥) def rsa_sign(message, private_key): key = RSA.import_key(private_key) h = SHA256.new(message.encode()) signature = pkcs1_15.new(key).sign(h) return signature # 验证(使用公钥) def rsa_verify(message, signature, public_key): key = RSA.import_key(public_key) h = SHA256.new(message.encode()) try: pkcs1_15.new(key).verify(h, signature) return True except (ValueError, TypeError): return False
优势:
from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.backends import default_backend # 生成 ECC 密钥对 private_key = ec.generate_private_key(ec.SECP256R1(), default_backend()) public_key = private_key.public_key() # ECDH 密钥交换 shared_key = private_key.exchange(ec.ECDH(), peer_public_key)
import hashlib def sha256_hash(message): return hashlib.sha256(message.encode()).hexdigest() # 示例 message = "Hello, World!" hash_value = sha256_hash(message) print(f"SHA-256: {hash_value}")
import hmac def hmac_sha256(message, key): return hmac.new(key.encode(), message.encode(), hashlib.sha256).hexdigest() # 示例 message = "Important message" key = "secret_key" signature = hmac_sha256(message, key) print(f"HMAC: {signature}")
PBKDF2:
import os from Crypto.Protocol.KDF import PBKDF2 def derive_key(password, salt, iterations=100000): return PBKDF2(password, salt, dkLen=32, count=iterations) # 使用示例 password = "my_secure_password".encode() salt = os.urandom(16) derived_key = derive_key(password, salt)
Argon2(推荐):
from argon2 import PasswordHasher ph = PasswordHasher( time_cost=3, # 迭代次数 memory_cost=65536, # 内存使用(KB) parallelism=4, # 并行度 hash_len=32, # 输出长度 salt_len=16 # 盐长度 ) # 哈希密码 hashed = ph.hash("my_password") # 验证密码 try: ph.verify(hashed, "my_password") print("密码正确") except: print("密码错误")
握手过程:
最佳实践:
import bcrypt # 哈希密码 password = "my_secure_password".encode() salt = bcrypt.gensalt(rounds=12) hashed = bcrypt.hashpw(password, salt) # 验证密码 if bcrypt.checkpw(password, hashed): print("密码正确")
文件加密:
from Crypto.Cipher import AES from Crypto.Random import get_random_bytes def encrypt_file(input_file, output_file, key): iv = get_random_bytes(16) cipher = AES.new(key, AES.MODE_GCM, nonce=iv) with open(input_file, 'rb') as f_in, open(output_file, 'wb') as f_out: f_out.write(iv) while True: chunk = f_in.read(65536) if not chunk: break ciphertext, tag = cipher.encrypt_and_digest(chunk) f_out.write(ciphertext + tag)
密码学是信息安全的基石:
记住:加密只是安全的一部分,还需要结合其他安全措施!