密码学实战:从古典密码到现代加密算法


文档摘要

密码学实战:从古典密码到现代加密算法 密码学基础 核心概念 机密性(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):发送方无法否认

古典密码

凯撒密码(Caesar Cipher)

原理:字母表移位

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

维吉尼亚密码(Vigenère Cipher)

原理:使用关键词进行多表替换

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

对称加密

AES(Advanced Encryption Standard)

特点

  • 分组密码:128 位分组
  • 密钥长度:128/192/256 位
  • 安全、高效、广泛应用

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}")

加密模式

ECB 模式(不推荐)

  • 独立加密每个分组
  • 相同明文产生相同密文
  • 不安全

CBC 模式(推荐)

  • 需要初始化向量(IV)
  • 链式加密
  • IV 必须随机且不可预测

GCM 模式(推荐)

  • 认证加密
  • 同时保证机密性和完整性
  • 支持并行
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()

非对称加密

RSA

原理:基于大整数分解困难问题

密钥生成

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

ECC(椭圆曲线密码)

优势

  • 更短的密钥长度
  • 更快的计算速度
  • 相同安全级别
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)

哈希函数

SHA-256

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}")

HMAC(基于哈希的消息认证码)

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("密码错误")

实际应用

1. HTTPS/TLS

握手过程

  1. 客户端发送支持的密码套件
  2. 服务器选择密码套件并发送证书
  3. 客户端验证证书
  4. 密钥交换(RSA/ECDHE)
  5. 使用对称加密通信

2. 密码存储

最佳实践

  • 使用 Argon2/bcrypt/scrypt
  • 每个密码使用随机盐
  • 适当的迭代次数/内存成本
import bcrypt # 哈希密码 password = "my_secure_password".encode() salt = bcrypt.gensalt(rounds=12) hashed = bcrypt.hashpw(password, salt) # 验证密码 if bcrypt.checkpw(password, hashed): print("密码正确")

3. 数据加密

文件加密

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)

安全最佳实践

  1. 永远不要自己设计加密算法
  2. 使用标准库和经过验证的算法
  3. 密钥管理至关重要
  4. 及时更新加密库
  5. 定期进行安全审计

总结

密码学是信息安全的基石:

  1. 理解基础:掌握核心概念和原理
  2. 选择算法:根据场景选择合适的算法
  3. 正确实现:避免常见的安全漏洞
  4. 密钥管理:安全存储和管理密钥
  5. 持续学习:密码学领域不断发展

记住:加密只是安全的一部分,还需要结合其他安全措施!


发布者: 作者: 转发
评论区 (0)
U