AES 加密百科完全指南
AES(Advanced Encryption Standard,高级加密标准)是目前世界上最广泛使用的对称分组密码算法。它由比利时密码学家 Joan Daemen 和 Vincent Rijmen 设计(原名 Rijndael),2001 年由 NIST 正式发布为 FIPS 197 标准,取代了已不安全的 DES。
AES 的核心优势:
- 安全性高:至今无可行的密码分析攻击攻破全轮 AES
- 性能卓越:纯查表/硬件加速(AES-NI)可达到数 GB/s
- 灵活性:支持 128/192/256 位密钥,多种工作模式
- 广泛部署:TLS、SSH、Wi-Fi (WPA2)、磁盘加密 (BitLocker/LUKS/FileVault)、JWT、VPN、ZIP/AES 等
一、AES 概述
1.1 参数概览
| 属性 | AES-128 | AES-192 | AES-256 |
|---|---|---|---|
| 密钥长度 | 128 位 (16 字节) | 192 位 (24 字节) | 256 位 (32 字节) |
| 分组大小 | 128 位 (16 字节) | 128 位 | 128 位 |
| 轮数 | 10 轮 | 12 轮 | 14 轮 |
| 初始轮 | AddRoundKey | AddRoundKey | AddRoundKey |
| 每轮操作 | SubBytes, ShiftRows, MixColumns, AddRoundKey | 同上 | 同上 |
| 末轮 | 无 MixColumns | 无 MixColumns | 无 MixColumns |
| S-box 大小 | 16×16 = 256 字节 | 相同 | 相同 |
| 密钥扩展表 | 44 个 32 位字 (176 字节) | 52 个 (208 字节) | 60 个 (240 字节) |
1.2 状态矩阵(State)
AES 将 16 字节的数据视为 4×4 字节矩阵(列主序填充):
输入: B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 B10 B11 B12 B13 B14 B15
状态矩阵 (列主序 = 按列填充):
┌ ┐
│ B0 B4 B8 B12 │
│ B1 B5 B9 B13 │
│ B2 B6 B10 B14│
│ B3 B7 B11 B15│
└ ┘
col0 col1 col2 col3
注意:这是列主序(column-major)填充,即先填满第一列,再第二列…不是行主序!
1.3 一轮 AES 完整流程
总轮数:
| 算法 | 轮数 | 轮密钥个数 |
|---|---|---|
| AES-128 | 10 | 11 (含初始轮) |
| AES-192 | 12 | 13 |
| AES-256 | 14 | 15 |
二、核心操作详解(四大步骤)
2.1 SubBytes(字节替换 / S-box 查表)
核心:每个字节独立通过 S-box 查表替换。S-box 是 16×16 的固定查找表。
S-box 构造原理:
S-box(x) = A · x⁻¹ + b
其中:
x⁻¹ = x 在 GF(2^8) 中的乘法逆元 (0 的逆元规定为 0)
A = 固定的 8×8 位矩阵 (仿射变换)
b = 固定的 8 位常数 (0x63)
设计目标:
- 非线性 (S-box 不是线性的 → 抗差分/线性攻击)
- 雪崩效应:1 位明文变化→至少 32 位密文变化
- 无固定点 (S-box[x] ≠ x, 对所有 x)
**S-box 表 (16×16)**:
按高 4 位作行索引, 低 4 位作列索引:
0 1 2 3 4 5 6 7 8 9 A B C D E F
─────────────────────────────────────────────────────────────────
0: 63 7C 77 7B F2 6B 6F C5 30 01 67 2B FE D7 AB 76
1: 1 CA 82 C9 7D FA 59 47 F0 AD D4 A2 AF 9C A4 72
2: C0 B7 FD 93 26 36 3F F7 CC 34 A5 E5 F1 71 D8 31
3: 15 04 C7 23 C3 18 96 05 9A 07 12 80 E2 EB 27 B2
4: 75 09 83 2C 1A 1B 6E 5A A0 52 3B D6 B3 29 E3 2F
5: 84 53 D1 00 ED 20 FC B1 5B 6A CB BE 39 4A 4C 58
6: CF D0 EF AA FB 43 4D 33 85 45 F9 02 7F 50 3C 9F
7: A8 51 A3 40 8F 92 9D 38 F5 BC B6 DA 21 10 FF F3
8: D2 CD 0C 13 EC 5F 97 44 17 C4 A7 7E 3D 64 5D 19
9: 73 60 81 4F DC 22 2A 90 88 46 EE B8 14 DE 5E 0B
A: DB E0 32 3A 0A 49 06 24 5C C2 D3 AC 62 91 95 E4
B: 79 E7 C8 37 6D 8D D5 4E A9 6C 56 F4 EA 65 7A AE
C: 08 BA 78 25 2E 1C A6 B4 C6 E8 DD 74 1F 4B BD 8B
D: 8A 00 70 3E B5 66 48 03 F6 0E 61 35 57 B9 86 C1
E: 1D 9E E1 F8 98 11 69 D9 8E 94 9B 1E 87 E9 CE 54
F: 69 0D 98 11 69 B5 CB 7E EA 1E 8E 94 9B 1E 87 E9 CE 54
(简化版本,完整表请参阅 FIPS 197)
示例: S-box[0x00] = 0x63, S-box[0x01] = 0x7c, S-box[0x41] = 0x83
Python 实现:
# AES S-box (标准表, 256 字节)
SBOX = [
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x00,0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,
0x9e,0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x54,0x0d,
0x98,0x11,0x69,0xb5,0xcb,0x7e,0xea,0x1e,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x54,
]
def sub_bytes(state):
"""对状态矩阵的每个字节进行 S-box 替换"""
return [[SBOX[byte] for byte in row] for row in state]
**逆 S-box (InvS-box)**:与 S-box 相反映射,用于解密。
2.2 ShiftRows(行移位)
核心:状态矩阵的每行循环左移不同位数
┌ ┐ ┌ ┐
│ s0 s4 s8 s12│ 行0 │ s0 s4 s8 s12│ (不移位)
│ s1 s5 s9 s13│ 行1 │ s5 s9 s13 s1│ (左移 1 字节)
│ s2 s6 s10 s14│ 行2 │ s10 s14 s2 s6│ (左移 2 字节)
│ s3 s7 s11 s15│ 行3 │ s15 s3 s7 s11│ (左移 3 字节)
└ ┘ └ ┘
Python 实现:
def shift_rows(state):
"""行移位: 每行循环左移 row_number 个位置"""
new_state = [row[:] for row in state]
for i in range(1, 4):
new_state[i] = new_state[i][i:] + new_state[i][:i]
return new_state
逆操作 InvShiftRows:每行循环右移对应位数。
2.3 MixColumns(列混合)
核心:每列视为 GF(2^8) 上的多项式,与固定多项式相乘。
数学原理:
在 GF(2^8) 有限域中,每列与下列矩阵相乘:
[ 2 3 1 1 ] [ s0 ]
[ 1 2 3 1 ] [ s1 ]
[ 1 1 2 3 ] [ s2 ]
[ 3 1 1 2 ] [ s3 ]
GF(2^8) 乘法规则:
- 加法 = XOR
- 乘法 = 多项式乘法模 AES 规约多项式 (x^8 + x^4 + x^3 + x + 1, 即 0x11B)
Python 实现:
def gf_mul(a, b):
"""GF(2^8) 乘法 (Rijndael 算法)"""
result = 0
for _ in range(8):
if b & 1:
result ^= a
high_bit = a & 0x80
a = (a << 1) & 0xff
if high_bit:
a ^= 0x1b # 规约多项式: x^4+x^3+x+1
b >>= 1
return result
# MixColumns 矩阵
MC_MATRIX = [
[2, 3, 1, 1],
[1, 2, 3, 1],
[1, 1, 2, 3],
[3, 1, 1, 2],
]
def mix_columns(state):
"""列混合: 对每列进行矩阵乘法"""
new_state = [[0]*4 for _ in range(4)]
for col in range(4):
for row in range(4):
new_state[row][col] = (
gf_mul(MC_MATRIX[row][0], state[0][col])
^ gf_mul(MC_MATRIX[row][1], state[1][col])
^ gf_mul(MC_MATRIX[row][2], state[2][col])
^ gf_mul(MC_MATRIX[row][3], state[3][col])
)
return new_state
# 逆矩阵 (InvMixColumns)
INV_MC_MATRIX = [
[0xe, 0xb, 0xd, 0x9],
[0x9, 0xe, 0xb, 0xd],
[0xd, 0x9, 0xe, 0xb],
[0xb, 0xd, 0x9, 0xe],
]
def inv_mix_columns(state):
new_state = [[0]*4 for _ in range(4)]
for col in range(4):
for row in range(4):
new_state[row][col] = (
gf_mul(INV_MC_MATRIX[row][0], state[0][col])
^ gf_mul(INV_MC_MATRIX[row][1], state[1][col])
^ gf_mul(INV_MC_MATRIX[row][2], state[2][col])
^ gf_mul(INV_MC_MATRIX[row][3], state[3][col])
)
return new_state
特殊情况:末轮没有 MixColumns(只有 SubBytes → ShiftRows → AddRoundKey),这是为了让加密和解密结构对称,便于硬件实现。
2.4 AddRoundKey(轮密钥加)
核心:状态矩阵与对应的 16 字节轮密钥逐字节 XOR。
def add_round_key(state, round_key):
"""将状态矩阵与轮密钥 XOR"""
new_state = [[0]*4 for _ in range(4)]
for row in range(4):
for col in range(4):
# round_key 按列存储: [col0_word, col1_word, col2_word, col3_word]
new_state[row][col] = state[row][col] ^ round_key[col][row]
return new_state
轮密钥来源:由原始密钥通过密钥扩展(Key Expansion)算法生成。
三、密钥扩展(Key Expansion)
3.1 原理
原始密钥(16/24/32 字节)扩展为更多轮密钥:
AES-128: 16 字节密钥 → 扩展为 11 × 16 = 176 字节轮密钥 (44 个 32-bit words)
AES-192: 24 字节密钥 → 扩展为 13 × 16 = 208 字节轮密钥 (52 words)
AES-256: 32 字节密钥 → 扩展为 15 × 16 = 240 字节轮密钥 (60 words)
3.2 轮常数(Rcon)
每一轮密钥扩展使用固定的轮常数(Rcon):
RCON = [
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80,
0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f,
]
Rcon[i] = x^(i-1) in GF(2^8),即:
- Rcon[1] = 0x01 = x^0
- Rcon[2] = 0x02 = x^1
- Rcon[3] = 0x04 = x^2
- …
3.3 密钥扩展算法(AES-128)
输入: 16 字节密钥 K = [w0, w1, w2, w3] (每个 w 是 4 字节 = 32 位 word)
输出: 44 个 words = W[0..43]
W[0..3] = 原始密钥 (每 4 字节为一个 word)
for i from 4 to 43:
if i % 4 != 0:
W[i] = W[i-4] XOR W[i-1]
else:
W[i] = W[i-4] XOR SubWord(RotWord(W[i-1])) XOR Rcon[i/4]
子函数:
RotWord([a,b,c,d]) = [b,c,d,a] (循环左移 1 字节)
SubWord([a,b,c,d]) = [S-box[a], S-box[b], S-box[c], S-box[d]]
3.4 Python 实现(完整)
def rot_word(word):
"""[a,b,c,d] -> [b,c,d,a]"""
return word[1:] + word[:1]
def sub_word(word):
"""对 word 的每个字节进行 S-box 替换"""
return [SBOX[b] for b in word]
def key_expansion(key, key_bits=128):
"""密钥扩展
Args:
key: bytes (16/24/32 字节)
key_bits: 128/192/256
Returns:
list of 4-byte words, 共 44/52/60 个 words
"""
# Nk = 密钥的 word 数 (4/6/8)
if key_bits == 128:
Nk, Nr = 4, 10
elif key_bits == 192:
Nk, Nr = 6, 12
elif key_bits == 256:
Nk, Nr = 8, 14
else:
raise ValueError("Unsupported key size")
Nb = 4 # 每个块的 word 数固定为 4
total_words = Nb * (Nr + 1) # 需要的总 words
W = []
# 初始 words = 密钥本身
for i in range(Nk):
W.append(list(key[i*4:(i+1)*4]))
# 扩展剩余 words
for i in range(Nk, total_words):
temp = W[i-1][:]
if i % Nk == 0:
temp = sub_word(rot_word(temp))
temp[0] ^= RCON[i // Nk]
elif Nk > 6 and i % Nk == 4: # AES-256 特殊: 多一次 SubWord
temp = sub_word(temp)
# W[i] = W[i-Nk] XOR temp
word = [a ^ b for a, b in zip(W[i-Nk], temp)]
W.append(word)
return W
验证测试:
# AES-128 标准测试向量 (FIPS 197 Appendix B)
key = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c")
W = key_expansion(key, 128)
# W[0] = [0x2b,0x7e,0x15,0x16] (原始密钥第一 word)
# W[4] 第一个扩展 word = W[0] XOR SubWord(RotWord(W[3])) XOR Rcon[1]
四、完整 AES 加密流程(AES-128 示例)
4.1 标准测试向量(FIPS 197, Appendix B)
密钥: 2b7e1516 28aed2a6 abf71588 09cf4f3c
明文: 3243f6a8 885a308d 313198a2 e0370734
密文: 3925841d 02dc09fb dc118597 196a0b32
4.2 手动追踪(加密过程)
步骤 1: 明文填到状态矩阵
明文: 32 43 f6 a8 88 5a 30 8d 31 31 98 a2 e0 37 07 34
状态矩阵 (列主序):
┌ ┐
│ 32 88 31 e0 │ ← 行0 (s0)
│ 43 5a 31 37 │ ← 行1 (s1)
│ f6 30 98 07 │ ← 行2 (s2)
│ a8 8d a2 34 │ ← 行3 (s3)
└ ┘
col0 col1 col2 col3
步骤 2: 初始 AddRoundKey (轮密钥 0)
轮密钥 0 = 原始密钥本身:
2b 7e 15 16
28 ae d2 a6
ab f7 15 88
09 cf 4f 3c
状态 XOR 轮密钥 0 = 新状态
步骤 3: 轮 1-9 (完整轮)
对每一轮执行: SubBytes → ShiftRows → MixColumns → AddRoundKey
步骤 4: 末轮(轮 10,无 MixColumns)
SubBytes → ShiftRows → AddRoundKey
步骤 5: 输出密文
4.3 完整 Python AES-128 实现(纯 Python,教育用途)
def bytes_to_state(data):
"""16 字节 → 4×4 状态矩阵 (列主序)"""
state = [[0]*4 for _ in range(4)]
for i in range(16):
state[i % 4][i // 4] = data[i]
return state
def state_to_bytes(state):
"""4×4 状态矩阵 → 16 字节"""
data = bytearray(16)
for i in range(16):
data[i] = state[i % 4][i // 4]
return bytes(data)
def aes_encrypt_block(block, key, key_bits=128):
"""单个 16 字节块 AES 加密"""
if key_bits == 128:
Nr = 10
elif key_bits == 192:
Nr = 12
elif key_bits == 256:
Nr = 14
# 步骤 1: 初始化状态矩阵
state = bytes_to_state(block)
# 步骤 2: 密钥扩展
W = key_expansion(key, key_bits)
# 步骤 3: 初始 AddRoundKey (轮 0)
round_key = [W[0], W[1], W[2], W[3]]
state = add_round_key(state, round_key)
# 步骤 4: 轮 1 到轮 Nr-1 (完整轮)
for round_num in range(1, Nr):
state = sub_bytes(state)
state = shift_rows(state)
state = mix_columns(state)
round_key = [W[round_num*4], W[round_num*4+1], W[round_num*4+2], W[round_num*4+3]]
state = add_round_key(state, round_key)
# 步骤 5: 末轮 (无 MixColumns)
state = sub_bytes(state)
state = shift_rows(state)
round_key = [W[Nr*4], W[Nr*4+1], W[Nr*4+2], W[Nr*4+3]]
state = add_round_key(state, round_key)
# 步骤 6: 输出
return state_to_bytes(state)
# 测试: FIPS 197 Appendix B
key = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c")
plaintext = bytes.fromhex("3243f6a8885a308d313198a2e0370734")
ciphertext = aes_encrypt_block(plaintext, key, 128)
print(f"Expected: 3925841d02dc09fbdc118597196a0b32")
print(f"Got: {ciphertext.hex()}")
# 应当一致
4.4 解密流程
解密是加密的逆过程:
密文
↓
AddRoundKey (轮 Nr)
↓
InvShiftRows
↓
InvSubBytes
↓
AddRoundKey (轮 Nr-1)
↓
InvMixColumns
↓
... (循环 Nr-1 次)
↓
InvShiftRows (轮 1)
↓
InvSubBytes
↓
AddRoundKey (轮 0)
↓
明文
五、AES 工作模式
5.1 模式概览
| 模式 | 全称 | 说明 | 认证? | 推荐? |
|---|---|---|---|---|
| ECB | Electronic Codebook | 各块独立加密 | 否 | ❌ 绝不推荐 |
| CBC | Cipher Block Chaining | 链式依赖,需 IV | 否 | ⚠️ 仅兼容 |
| CFB | Cipher Feedback | 转化为流密码 | 否 | ⚠️ 兼容 |
| OFB | Output Feedback | 转化为流密码 | 否 | ⚠️ 兼容 |
| CTR | Counter | 计数器模式,可并行 | 否 | ✅ 高级用法(配合认证) |
| GCM | Galois/Counter Mode | CTR + GHASH 认证 | 是 | ✅ 推荐 |
| CCM | Counter with CBC-MAC | CTR + CBC-MAC | 是 | ✅ Wi-Fi WPA2/WPA3 |
| XTS | XEX Tweakable Block Cipher | 磁盘加密专用 | 否 | ✅ 磁盘加密 |
| CBC-HMAC | CBC + HMAC | 加密+认证组合 | 是 | ⚠️ TLS 1.2 遗留 |
| ChaCha20-Poly1305 | Stream + Poly1305 | 非 AES,但常伴生 | 是 | ✅ 移动设备 |
5.2 ECB(不推荐)
原理:每个 16 字节块独立加密
C[i] = AES(K, P[i])
问题:相同明文块 → 相同密文块,泄露明文结构模式
明文块: A A B A A B (重复块明显可见)
ECB密文: X X Y X X Y (相同模式,泄露信息)
ECB 的可视化漏洞:对图像加密时,原图像的高频结构仍可在密文中识别。
5.3 CBC(Cipher Block Chaining)
原理:每个明文块先与前一个密文块 XOR,再加密
需要: 16 字节随机 IV (Initialization Vector)
C[0] = AES(K, P[0] XOR IV)
C[1] = AES(K, P[1] XOR C[0])
C[2] = AES(K, P[2] XOR C[1])
...
解密:
P[0] = AES^-1(K, C[0]) XOR IV
P[i] = AES^-1(K, C[i]) XOR C[i-1]
CBC 的特点:
- ✅ 相同明文块在不同位置产生不同密文
- ⚠️ 需要随机且不可预测的 IV
- ⚠️ 不可并行加密(但解密可并行)
- ❌ Padding Oracle 攻击(如果用 PKCS#7 填充,认证不当可被攻击)
- ❌ 本身不提供消息认证
**Python 示例 (PyCryptodome)**:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
def aes_cbc_encrypt(plaintext, key):
"""AES-CBC 加密"""
iv = get_random_bytes(16) # 16 字节随机 IV
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
return iv + ciphertext # 通常将 IV 附在密文前
def aes_cbc_decrypt(data, key):
"""AES-CBC 解密"""
iv = data[:16]
ciphertext = data[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext
key = get_random_bytes(16) # AES-128
msg = b"Hello, AES-CBC!"
encrypted = aes_cbc_encrypt(msg, key)
decrypted = aes_cbc_decrypt(encrypted, key)
assert decrypted == msg
Padding(填充):AES 块大小 16 字节,若明文不是 16 的倍数需要填充。
PKCS#7 填充(最常用):缺 N 字节则每个字节填充 N。
明文长度 14 → 缺 2 字节 → 填充 0x02 0x02
明文长度 16 → 额外补 16 字节 0x10
明文长度 10 → 缺 6 字节 → 填充 0x06×6
5.4 CTR(Counter Mode)
原理:将 AES 作为流密码使用,加密一个递增的计数器。
Nonce (固定) + Counter (递增) = 输入块
C[i] = P[i] XOR AES(K, Nonce || Counter[i])
结构:
优点:
- ✅ 完全可并行(加密和解密都可并行)
- ✅ 不需要填充
- ✅ 加解密结构相同(都是 XOR 密钥流)
- ✅ 随机访问(可以解密中间块,不需要前面所有块)
缺点:
- ❌ 计数器必须唯一:(Key, Nonce) 对绝不能重复使用,否则明文直接泄露!
- ❌ 不提供认证(需搭配 MAC 如 HMAC)
5.5 GCM(Galois/Counter Mode)(推荐)
原理:CTR 模式加密 + GHASH 多项式认证 = AEAD(Authenticated Encryption with Associated Data)
提供:
- 机密性(通过 CTR 加密)
- 完整性/真实性(通过 GHASH 认证标签)
- 关联数据(Associated Data, AD):已认证但不加密的数据
GCM 结构:
参数: 密钥 K, 12 字节 IV (推荐), 明文 P, 关联数据 A
输出: 密文 C, 16 字节认证标签 T
步骤 1: CTR 模式加密 P → C
步骤 2: 计算 GHASH(H, A, C) = 认证标签 T (在 GF(2^128) 上的多项式哈希)
完整输出: IV || C || T
GCM 的安全要点:
- ✅ IV 必须 12 字节且随机(标准推荐)
- ❌ (K, IV) 对绝对不能重复(重用 = 明文泄露 + 伪造攻击)
- ❌ 认证失败时绝对不能解密密文(需密文盲化处理)
**Python (PyCryptodome)**:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import json, base64
def aes_gcm_encrypt(plaintext, key, associated_data=b""):
"""AES-GCM 加密
返回 dict 含 nonce, ciphertext, tag"""
cipher = AES.new(key, AES.MODE_GCM)
if associated_data:
cipher.update(associated_data)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
return {
"nonce": base64.b64encode(cipher.nonce).decode(),
"tag": base64.b64encode(tag).decode(),
"ciphertext": base64.b64encode(ciphertext).decode(),
}
def aes_gcm_decrypt(encrypted, key, associated_data=b""):
"""AES-GCM 解密, 认证失败抛异常"""
nonce = base64.b64decode(encrypted["nonce"])
tag = base64.b64decode(encrypted["tag"])
ciphertext = base64.b64decode(encrypted["ciphertext"])
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
if associated_data:
cipher.update(associated_data)
try:
return cipher.decrypt_and_verify(ciphertext, tag)
except ValueError:
raise Exception("认证失败: 数据被篡改或密钥错误")
# 使用
key = get_random_bytes(32) # AES-256-GCM
msg = b"Hello, AES-GCM!"
ad = b"metadata: user=alice" # 已认证但不加密的附加数据
enc = aes_gcm_encrypt(msg, key, ad)
print(f"GCM 输出: {json.dumps(enc, indent=2)}")
dec = aes_gcm_decrypt(enc, key, ad)
print(f"解密成功: {dec}")
# 篡改测试
enc_bad = enc.copy()
enc_bad["ciphertext"] = "AAAA" + enc["ciphertext"][4:]
try:
aes_gcm_decrypt(enc_bad, key, ad)
except Exception as e:
print(f"篡改被正确检测: {e}")
GCM 的性能:硬件支持 AES-NI + PCLMULQDQ 指令时,吞吐可达 10 GB/s 级别。
5.6 XTS(磁盘加密专用)
原理:XEX-based tweaked-codebook mode with ciphertext stealing
专为随机访问的块设备设计(如磁盘扇区、SSD 页):
- 每个扇区有独立的 “tweak”(基于扇区号)
- 不需要 IV(用扇区号代替)
- 支持任意长度(不完全是 16 字节倍数也 OK)
- 密文窃取(Ciphertext Stealing) 处理最后不足的块
C[i] = AES(K1, P[i] XOR T[i]) XOR T[i]
T[i] = AES(K2, i) (i 是扇区/块编号)
应用:BitLocker、LUKS、FileVault、Android 全盘加密
5.7 模式对比小结
| 特性 | ECB | CBC | CTR | GCM | XTS |
|---|---|---|---|---|---|
| 认证 | ❌ | ❌ | ❌ | ✅ | ❌ |
| 并行加密 | ✅ | ❌ | ✅ | ✅ | ✅ |
| 并行解密 | ✅ | ✅ | ✅ | ✅ | ✅ |
| 随机访问 | ✅ | ❌ | ✅ | ✅ | ✅ |
| 需要填充 | ✅ | ✅ | ❌ | ❌ | ❌(密文窃取) |
| IV 重用后果 | 相同明文泄露 | 部分泄露 | 灾难性 | 灾难性 | 无(扇区ID) |
| 推荐用途 | 无 | 旧系统兼容 | 高级使用 | 通用首选 | 磁盘加密 |
六、Python AES 实战
6.1 使用 PyCryptodome(推荐)
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Hash import HMAC, SHA256
import base64, os, json
安装:
pip install pycryptodome
6.2 密钥派生(从口令到密钥)
不要直接用文本当密钥!使用 KDF:
def derive_key(password, salt=None, iterations=100000, dkLen=32):
"""PBKDF2-HMAC-SHA256 派生密钥"""
if salt is None:
salt = os.urandom(16)
key = PBKDF2(
password.encode(),
salt,
dkLen=dkLen,
count=iterations,
hmac_hash_module=SHA256
)
return key, salt
# 使用
password = "MySecurePassword123!"
key, salt = derive_key(password)
print(f"Salt: {salt.hex()}")
print(f"Key: {key.hex()}")
6.3 文件加密(AES-256-GCM)
def encrypt_file(input_path, output_path, password):
"""GCM 模式加密文件"""
key, salt = derive_key(password)
nonce = os.urandom(12) # GCM 推荐 12 字节
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
# 读取并加密
with open(input_path, "rb") as f:
plaintext = f.read()
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
# 保存: salt (16) || nonce (12) || tag (16) || ciphertext
with open(output_path, "wb") as f:
f.write(salt)
f.write(nonce)
f.write(tag)
f.write(ciphertext)
print(f"已加密: {len(plaintext)} 字节 → {len(ciphertext)} 字节密文")
def decrypt_file(input_path, output_path, password):
"""GCM 模式解密文件"""
with open(input_path, "rb") as f:
salt = f.read(16)
nonce = f.read(12)
tag = f.read(16)
ciphertext = f.read()
key, _ = derive_key(password, salt=salt)
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
try:
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
except ValueError:
raise Exception("解密失败: 密码错误或文件被篡改!")
with open(output_path, "wb") as f:
f.write(plaintext)
print(f"已解密: {len(plaintext)} 字节")
# 测试
encrypt_file("document.txt", "document.enc", "MyPassword")
decrypt_file("document.enc", "document.dec", "MyPassword")
6.4 AES-CTR + HMAC (经典 Encrypt-then-MAC)
from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA256
from Crypto.Random import get_random_bytes
def encrypt_then_mac(plaintext, key_enc, key_mac):
"""Encrypt-then-MAC: 先加密, 后计算 MAC
业界推荐的组合方式"""
# 加密 (CTR 模式, 不需要 padding)
nonce = get_random_bytes(8) # 8 字节 nonce + 8 字节 counter
cipher = AES.new(key_enc, AES.MODE_CTR, nonce=nonce)
ciphertext = cipher.encrypt(plaintext)
# 计算 MAC (认证: nonce || ciphertext)
hmac = HMAC.new(key_mac, digestmod=SHA256)
hmac.update(nonce + ciphertext)
mac = hmac.digest()
return nonce + mac + ciphertext
def verify_then_decrypt(data, key_enc, key_mac):
"""先验证再解密"""
nonce = data[:8]
mac = data[8:40] # SHA256 = 32 字节
ciphertext = data[40:]
# 验证 MAC
hmac = HMAC.new(key_mac, digestmod=SHA256)
hmac.update(nonce + ciphertext)
try:
hmac.verify(mac)
except ValueError:
raise Exception("MAC 验证失败, 数据可能被篡改")
# 验证通过后解密
cipher = AES.new(key_enc, AES.MODE_CTR, nonce=nonce)
return cipher.decrypt(ciphertext)
6.5 使用 cryptography 库(现代、设计更好的 API)
pip install cryptography
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes, hmac, padding
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
import os
# AES-256-GCM 加密
def encrypt(plaintext, key):
iv = os.urandom(12)
cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return iv + encryptor.tag + ciphertext
def decrypt(data, key):
iv, tag, ciphertext = data[:12], data[12:28], data[28:]
cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend())
decryptor = cipher.decryptor()
return decryptor.update(ciphertext) + decryptor.finalize()
key = os.urandom(32)
ciphertext = encrypt(b"Hello, AES!", key)
plaintext = decrypt(ciphertext, key)
6.6 Fernet(最高级 API,最简单)
from cryptography.fernet import Fernet
import base64
# 生成密钥 (AES-128-CBC + HMAC-SHA256 + PBKDF2)
key = Fernet.generate_key()
f = Fernet(key)
# 加密
token = f.encrypt(b"Hello, Fernet!")
print(token)
# 解密
plaintext = f.decrypt(token)
print(plaintext)
七、OpenSSL 命令行
7.1 加密/解密
# AES-256-CBC 加密文件(带 salt + PBKDF)
openssl enc -aes-256-cbc -salt -in input.txt -out output.enc -pbkdf2
# 解密
openssl enc -d -aes-256-cbc -in output.enc -out output.txt -pbkdf2
# AES-256-GCM (较新版本 openssl 支持)
openssl enc -aes-256-gcm -salt -in input.txt -out output.enc -pbkdf2
7.2 查看 AES 支持
# 查看支持的加密算法
openssl enc -help
# 基准测试 AES 性能
openssl speed aes-128-cbc
openssl speed aes-256-gcm
# 查看 AES-NI 是否启用(在 /proc/cpuinfo 中查找 aes)
grep aes /proc/cpuinfo
7.3 AES 密钥格式
# 生成 256 位随机密钥
openssl rand -hex 32
# 生成加密密钥 + Base64 编码
openssl rand -base64 32
八、AES 安全分析
8.1 理论攻击强度
| 攻击类型 | AES-128 | AES-192 | AES-256 |
|---|---|---|---|
| 暴力破解 | 2^128 | 2^192 | 2^256 |
| 差分密码分析 | 对 6 轮有效 | 对 8 轮有效 | 对 8 轮有效 |
| 线性密码分析 | 对 7 轮有效 | 对 8 轮有效 | 对 9 轮有效 |
| Biclique 攻击 | 2^126.1 | 2^189.7 | 2^254.4 |
| 量子计算机 (Grover) | 2^64 | 2^96 | 2^128 |
Biclique 攻击(2011):目前已知最有效的理论攻击,但仅比暴力搜索快 ~4 倍,远不具实际威胁。
8.2 实际安全威胁
| 威胁 | 说明 | 防御 |
|---|---|---|
| 弱密钥 | 使用可预测的密钥、弱派生算法 | 使用密码学安全的随机数 (CSPRNG) |
| ECB 模式 | 结构泄露 | 用 GCM/CTR/CBC |
| IV/Nonce 重用 | CTR/GCM 中重用 (K, IV) = 明文泄露 | 每次随机生成 12 字节 IV |
| Padding Oracle | CBC 模式下通过错误提示还原明文 | 用 GCM 或 AEAD |
| 侧信道攻击 | 功耗/时序/电磁泄露 | AES-NI 固定时序、掩码、乱序执行 |
| 相关密钥攻击 | AES-256 有理论弱点,AES-192 也有 | 避免弱密钥方案,使用标准 KDF |
| 密钥管理 | 密钥存储/传输/轮换问题 | HSM/KMS/密钥分层 |
8.3 量子抗性
AES-256 对量子计算机具有实际抗性:
- Grover 算法将搜索空间从 2^256 降到 2^128
- 2^128 操作对量子计算机而言仍是不可行(需要的量子比特和相干时间极难实现)
推荐:长期安全 → AES-256,或考虑与后量子算法结合(NIST PQC 标准如 Kyber)
8.4 正确使用检查表
✅ 使用 AES-256-GCM(通用首选 AEAD)
✅ 使用 AES-256-XTS(磁盘加密)
✅ 使用 密码学安全随机数(os.urandom / get_random_bytes)
✅ GCM 使用 12 字节随机 IV,永不重复
✅ 标签认证成功后才解密(密文盲化)
✅ 密钥派生使用 Argon2id / PBKDF2 (≥100000 轮) / scrypt
❌ 不要使用 ECB 模式
❌ 不要 自制加密方案
❌ 不要 重复使用 (K, IV) 对
❌ 不要 直接用口令作为密钥(需经过 KDF)
❌ 不要 CBC + PKCS#7 填充没有 MAC(Padding Oracle)
九、AES 硬件加速(AES-NI)
9.1 原理
x86 架构 CPU 自 2010 年起支持 AES 指令集:
| 指令 | 功能 |
|---|---|
| AESENC | 执行一轮 AES 加密 |
| AESENCLAST | 执行末轮加密 |
| AESDEC | 执行一轮 AES 解密 |
| AESDECLAST | 执行末轮解密 |
| AESKEYGENASSIST | 辅助密钥扩展 |
| AESIMC | 逆列混合(解密准备) |
| PCLMULQDQ | 无进位乘法(GCM 所需 GHASH) |
9.2 性能
| 实现 | AES-128 吞吐 |
|---|---|
| 纯软件查表 | ~100-300 MB/s |
| AES-NI 软件 | ~1 GB/s |
| AES-NI + PCLMUL (GCM) | ~5-10 GB/s |
| AES 专用硬件 | 可达 100 GB/s+ |
9.3 在 Python 中自动启用
PyCryptodome 和 cryptography 库自动检测并使用 AES-NI,无需手动配置。
# 检查 CPU 是否支持 AES-NI
grep -o aes /proc/cpuinfo | head -1
# 或
sysctl -a | grep -i aes # macOS
十、CTF 实战:AES 相关题目
10.1 常见题目类型
| 题目类型 | 说明 |
|---|---|
| ECB Oracle | ECB 模式下逐字节解密 |
| CBC Padding Oracle | 利用填充错误解密任意密文 |
| IV Reuse | CBC/CTR 中重用 IV → 明文泄露 |
| Nonce Reuse (GCM/CTR) | 两次加密用同一 Nonce → 可求明文 XOR |
| Key Reuse | 用同一密钥加密不同长度的多组密文 |
| AES-CMAC 伪造 | CBC-MAC 扩展攻击 |
| 可预测 IV | 利用 CBC 模式的 IV 预测进行攻击 |
| Bit Flipping | CBC/CTR 模式下翻转密文位来篡改明文 |
10.2 CTR 模式 Nonce 重用攻击(经典)
# 假设: 攻击者获得两组 (P1, C1) 和 (P2, C2), 使用相同 (K, IV)
# 在 CTR 模式下:
# C1 = P1 XOR AES(K, IV||0)
# C2 = P2 XOR AES(K, IV||0)
# 所以: C1 XOR C2 = P1 XOR P2
# 如果已知 P1 (如标准 HTTP 头), 可恢复 P2!
def ctr_nonce_reuse_attack(c1, c2, known_plaintext_part):
"""当 (K,IV) 重用时, 从已知明文恢复未知明文"""
xor_c = bytes(a ^ b for a, b in zip(c1, c2))
# xor_c = p1 XOR p2
# 如果已知 p1 的一部分 (如 HTTP 头 "HTTP/1.1 200 OK")
# 则 p2 的对应部分 = xor_c XOR known_p1
...
10.3 Padding Oracle 攻击思路
1. 选择要解密的密文块 C[i]
2. 构造伪 IV (从 0x00 0x00 ... 0xNN 开始)
3. 发送 (伪 IV, C[i]) 给 Oracle
4. Oracle 返回 "Padding OK" 或 "Padding Error"
5. 根据返回逐字节推导明文
6. 复杂度: 每字节最多 256 次请求, 平均 128 次
十一、AES 常见问题 FAQ
Q1: AES-128, AES-192, AES-256 选哪个?
- 通用:AES-128 足够(安全到 2^128),且更快
- 高安全:AES-256(对量子攻击更保守,军用/金融级别)
- AES-192:较少使用(介于两者之间)
Q2: AES 会被破解吗?
- 目前不可能:理论攻击只针对 6-8 轮,全轮 AES 无可行攻击
- 量子威胁:AES-256 抗量子,AES-128 理论需 2^64 量子操作
Q3: 为什么 GCM 比 CBC 好?
- GCM 提供认证加密(机密性 + 完整性 + 真实性)
- GCM 可并行
- GCM 无填充问题(不会有 Padding Oracle)
- GCM 是当前业界推荐的通用模式
Q4: IV 和 Nonce 有什么区别?
- IV(初始化向量):CBC/OFB/CFB 使用,必须不可预测且随机
- Nonce(一次性数):CTR/GCM 使用,只要唯一即可(不一定要随机)
- 共同点:同一密钥下绝对不能重用
Q5: AES 和 RSA 的区别?
- AES:对称加密,速度快 (GB/s),用于加密数据
- RSA:非对称加密,速度慢 (MB/s 级别),用于密钥交换/签名
- 实际系统中:RSA + AES 组合使用(RSA 加密 AES 密钥,AES 加密数据)
Q6: 如何安全地存储 AES 密钥?
- 操作系统级:DPAPI (Windows), Keychain (macOS), Keyutils (Linux)
- 硬件级:HSM, TPM, YubiKey, AWS CloudHSM
- 云端:AWS KMS, Azure Key Vault, Google Cloud KMS
- 应用级:Vault, HashiCorp Vault
- 简单方案:AES 密钥用口令派生,口令不在磁盘存储
十二、AES-128 完整手动计算示例(FIPS 197)
输入:
- 明文:
3243f6a8885a308d313198a2e0370734 - 密钥:
2b7e151628aed2a6abf7158809cf4f3c - 期望密文:
3925841d02dc09fbdc118597196a0b32
初始状态矩阵(列主序):
[32 88 31 e0]
[43 5a 31 37]
[f6 30 98 07]
[a8 8d a2 34]
AddRoundKey(轮密钥 0):
轮密钥 0 = 密钥本身:
[2b 28 ab 09]
[7e ae f7 cf]
[15 d2 15 4f]
[16 a6 88 3c]
XOR 后:
[19 a0 9a e9]
[3d f4 c6 f8]
[e3 e2 8d 48]
[be 2b 2a 08]
轮 1 - SubBytes(S-box 查表):
S-box[19] = d4 S-box[a0] = e0 S-box[9a] = b8 S-box[e9] = 1e
S-box[3d] = 27 S-box[f4] = bf S-box[c6] = b4 S-box[f8] = 41
S-box[e3] = 11 S-box[e2] = 98 S-box[8d] = 5d S-box[48] = 52
S-box[be] = ae S-box[2b] = f1 S-box[2a] = e5 S-box[08] = 30
状态 →
[d4 e0 b8 1e]
[27 bf b4 41]
[11 98 5d 52]
[ae f1 e5 30]
轮 1 - ShiftRows:
行0: 不移动 → [d4 e0 b8 1e]
行1: 左移 1 → [bf b4 41 27]
行2: 左移 2 → [5d 52 11 98]
行3: 左移 3 → [30 ae f1 e5]
新状态:
[d4 e0 b8 1e]
[bf b4 41 27]
[5d 52 11 98]
[30 ae f1 e5]
轮 1 - MixColumns(列混合,GF(2^8) 矩阵乘法):
每列与 [2,3,1,1; 1,2,3,1; …] 相乘
轮 1 - AddRoundKey(与轮密钥 1 XOR)
… 继续到轮 10 …
最终输出(密文):
39 25 84 1d
02 dc 09 fb
dc 11 85 97
19 6a 0b 32
即:3925841d02dc09fbdc118597196a0b32(与 FIPS 197 测试向量一致)
总结
AES(Rijndael)是现代密码学的核心算法,特点是:
- 数学严谨:基于有限域 GF(2^8) 的精心设计(S-box / MixColumns)
- 结构简洁:四轮操作 + 密钥扩展,易于硬件/软件实现
- 性能卓越:配合 AES-NI 指令集,达到数 GB/s 吞吐
- 安全可靠:20 年全球密码分析无实际弱点
- 灵活多样:GCM/CTR/CBC/XTS 等模式覆盖几乎所有场景
推荐配置:
- 通用加密: AES-256-GCM(认证加密)
- 磁盘加密: AES-256-XTS(随机访问)
- 密钥派生: Argon2id 或 PBKDF2-HMAC-SHA256 (100000+ 轮)
- IV/Nonce: 12 字节随机,永不重复
使用原则:不要自己实现 AES,使用经审计的库(PyCryptodome / cryptography / OpenSSL)。重点放在正确的密钥管理和模式选择上,而不是算法本身。