# 密码学实战:从古典密码到AES,手把手教你用Python实现加密算法
在数字时代,数据安全的重要性不言而喻。无论是保护个人隐私还是企业机密,加密技术都扮演着至关重要的角色。本文将带您从最基础的古典密码开始,逐步深入到现代加密标准AES的实现,全程使用Python代码演示,让抽象的理论变得触手可及。
对于有一定Python基础的开发者来说,理解加密算法的实现原理不仅能提升编程能力,更能帮助我们在实际项目中做出更安全的设计决策。我们将避开枯燥的数学证明,专注于代码实现和可视化演示,让您在实践中掌握密码学的精髓。
## 1. 古典密码的Python实现
古典密码虽然在现代加密标准面前显得简单,但它们是理解加密思想的绝佳起点。让我们从最基础的凯撒密码开始,逐步构建更复杂的加密系统。
### 1.1 凯撒移位密码
凯撒密码是最著名的替换密码之一,其核心思想是将字母表中的每个字母移动固定的位数。以下是Python实现:
```python
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
elif char.islower():
result += chr((ord(char) + shift - 97) % 26 + 97)
else:
result += char
return result
# 示例使用
plaintext = "HelloWorld"
shift = 3
ciphertext = caesar_cipher(plaintext, shift)
print(f"加密结果: {ciphertext}") # 输出: KhoorZruog
decrypted = caesar_cipher(ciphertext, -shift)
print(f"解密结果: {decrypted}") # 输出: HelloWorld
```
> 注意:凯撒密码的密钥空间很小(只有25种可能),在现代安全要求下完全不适用,仅用于教学目的。
### 1.2 仿射密码进阶
仿射密码是凯撒密码的推广,使用线性代数中的仿射变换:
```python
def affine_cipher(text, a, b):
result = ""
for char in text.lower():
if char.isalpha():
x = ord(char) - 97
encrypted = (a * x + b) % 26
result += chr(encrypted + 97)
else:
result += char
return result
# 计算模逆函数
def modinv(a, m):
for x in range(1, m):
if (a * x) % m == 1:
return x
return None
# 示例使用
a, b = 7, 3
plaintext = "hot"
ciphertext = affine_cipher(plaintext, a, b)
print(f"加密结果: {ciphertext}") # 输出: "axq"
# 解密需要a的模逆
a_inv = modinv(a, 26)
decrypted = affine_cipher(ciphertext, a_inv, -a_inv * b % 26)
print(f"解密结果: {decrypted}") # 输出: "hot"
```
## 2. 现代对称加密:AES实现
AES(高级加密标准)是目前最常用的对称加密算法。Python的`pycryptodome`库提供了完善的AES实现。
### 2.1 AES基础加密
首先安装必要的库:
```bash
pip install pycryptodome
```
然后实现基本的ECB模式加密:
```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):
cipher = AES.new(key, AES.MODE_ECB)
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size))
return ciphertext
def aes_decrypt(ciphertext, key):
cipher = AES.new(key, AES.MODE_ECB)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext.decode()
# 示例使用
key = get_random_bytes(16) # AES-128
message = "Secret Message"
encrypted = aes_encrypt(message, key)
print(f"加密结果: {encrypted.hex()}")
decrypted = aes_decrypt(encrypted, key)
print(f"解密结果: {decrypted}")
```
> 警告:ECB模式存在安全性问题,相同的明文块会产生相同的密文块,实际应用中应避免使用。
### 2.2 更安全的CBC模式
CBC(密码块链接)模式通过引入初始化向量(IV)解决了ECB模式的问题:
```python
def aes_cbc_encrypt(plaintext, key):
iv = get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size))
return iv + ciphertext
def aes_cbc_decrypt(ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext[AES.block_size:]), AES.block_size)
return plaintext.decode()
# 示例使用
encrypted = aes_cbc_encrypt(message, key)
print(f"CBC加密结果: {encrypted.hex()}")
decrypted = aes_cbc_decrypt(encrypted, key)
print(f"CBC解密结果: {decrypted}")
```
## 3. 加密模式对比与选择
不同的加密模式有各自的优缺点,下面是主要模式的对比:
| 模式 | 安全性 | 并行加密 | 错误传播 | 典型用途 |
|------|--------|----------|----------|----------|
| ECB | 低 | 是 | 无 | 不推荐使用 |
| CBC | 中 | 否 | 有 | 文件加密、SSL/TLS |
| CTR | 高 | 是 | 无 | 网络通信、实时系统 |
| GCM | 高 | 是 | 无 | 需要认证的加密 |
在实际项目中,推荐使用AES-GCM模式,它同时提供加密和认证功能:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def aes_gcm_encrypt(plaintext, key):
cipher = AES.new(key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(plaintext.encode())
return cipher.nonce + tag + ciphertext
def aes_gcm_decrypt(ciphertext, key):
nonce = ciphertext[:16]
tag = ciphertext[16:32]
ciphertext = ciphertext[32:]
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
return plaintext.decode()
# 示例使用
encrypted = aes_gcm_encrypt(message, key)
print(f"GCM加密结果: {encrypted.hex()}")
decrypted = aes_gcm_decrypt(encrypted, key)
print(f"GCM解密结果: {decrypted}")
```
## 4. 实际应用中的注意事项
在真实项目中使用加密时,有几个关键点需要特别注意:
1. **密钥管理**:永远不要硬编码密钥在代码中,使用密钥管理系统或环境变量
2. **随机数生成**:加密相关的随机数必须使用加密安全的随机数生成器
3. **填充方案**:选择适当的填充方案,如PKCS#7
4. **认证加密**:优先选择提供认证的加密模式如GCM
以下是一个更完整的加密工具类实现:
```python
import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from base64 import b64encode, b64decode
class AESCipher:
def __init__(self, key=None):
self.key = key if key else get_random_bytes(32) # 默认使用AES-256
def encrypt(self, plaintext):
iv = get_random_bytes(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size))
return b64encode(iv + ciphertext).decode('utf-8')
def decrypt(self, encrypted):
encrypted = b64decode(encrypted)
iv = encrypted[:AES.block_size]
ciphertext = encrypted[AES.block_size:]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext.decode('utf-8')
# 使用示例
cipher = AESCipher()
secret = "Top Secret Data"
encrypted = cipher.encrypt(secret)
print(f"加密结果: {encrypted}")
decrypted = cipher.decrypt(encrypted)
print(f"解密结果: {decrypted}")
```
在开发需要加密功能的应用时,建议先进行威胁建模,明确需要保护的数据和可能的攻击向量。加密只是安全链条中的一环,还需要考虑安全传输、存储、访问控制等多方面因素。