AES128 加解密原理
AES(Advanced Encryption Standard)是一种对称加密算法,使用相同的密钥进行加密和解密。AES128 密钥长度为 128 位(16 字节),加密过程分为多轮(10 轮),每轮包括字节代换、行移位、列混淆和轮密钥加。
AES128 加密步骤
-
密钥扩展
通过 Rijndael 密钥调度算法将初始 128 位密钥扩展为 11 个 128 位轮密钥(包括初始轮密钥)。 -
初始轮密钥加
将明文与第 1 个轮密钥进行异或操作。 -
轮函数(重复 10 轮)
- 字节代换(SubBytes):通过 S 盒将每个字节非线性替换。
- 行移位(ShiftRows):对每行字节循环左移不同位数。
- 列混淆(MixColumns):对每列进行矩阵乘法(GF(2⁸)域)。
- 轮密钥加(AddRoundKey):与当前轮密钥异或。
-
最终轮(省略列混淆)
执行字节代换、行移位和轮密钥加。
AES128 解密步骤
解密是加密的逆过程,顺序如下:
-
初始轮密钥加
使用第 10 个轮密钥与密文异或。 -
轮函数(重复 10 轮)
- 逆行移位(InvShiftRows):右移恢复原始位置。
- 逆字节代换(InvSubBytes):通过逆 S 盒还原字节。
- 轮密钥加(AddRoundKey):与轮密钥异或(逆序使用)。
- 逆列混淆(InvMixColumns):通过逆矩阵乘法还原列。
-
最终轮(省略逆列混淆)
执行逆行移位、逆字节代换和轮密钥加。
代码实现(Python)
以下是使用 pycryptodome
库的示例代码:
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_CBC)
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
return cipher.iv, ciphertext
# 解密
def aes_decrypt(iv, ciphertext, key):
cipher = AES.new(key, AES.MODE_CBC, iv=iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext
# 示例
key = get_random_bytes(16) # 128-bit key
plaintext = b"Hello, AES128!"
iv, ciphertext = aes_encrypt(plaintext, key)
decrypted = aes_decrypt(iv, ciphertext, key)
print("Decrypted:", decrypted.decode())
数学基础
AES 的核心运算基于有限域 GF(2⁸),定义不可约多项式为: $$ m(x) = x^8 + x^4 + x^3 + x + 1 $$
列混淆的矩阵乘法公式(加密): $$ \begin{pmatrix} 02 & 03 & 01 & 01 \ 01 & 02 & 03 & 01 \ 01 & 01 & 02 & 03 \ 03 & 01 & 01 & 02 \ \end{pmatrix} $$
注意事项
-
填充模式
AES 块大小为 16 字节,明文需填充至整数倍(如 PKCS7)。 -
初始化向量(IV)
CBC 模式需随机生成 IV,确保相同明文加密结果不同。 -
密钥安全
密钥需通过安全方式存储或传输(如密钥派生函数)。