详解 AES128 加解密

AES128 加解密原理

AES(Advanced Encryption Standard)是一种对称加密算法,使用相同的密钥进行加密和解密。AES128 密钥长度为 128 位(16 字节),加密过程分为多轮(10 轮),每轮包括字节代换、行移位、列混淆和轮密钥加。

AES128 加密步骤

  1. 密钥扩展
    通过 Rijndael 密钥调度算法将初始 128 位密钥扩展为 11 个 128 位轮密钥(包括初始轮密钥)。

  2. 初始轮密钥加
    将明文与第 1 个轮密钥进行异或操作。

  3. 轮函数(重复 10 轮)

    • 字节代换(SubBytes):通过 S 盒将每个字节非线性替换。
    • 行移位(ShiftRows):对每行字节循环左移不同位数。
    • 列混淆(MixColumns):对每列进行矩阵乘法(GF(2⁸)域)。
    • 轮密钥加(AddRoundKey):与当前轮密钥异或。
  4. 最终轮(省略列混淆)
    执行字节代换、行移位和轮密钥加。

AES128 解密步骤

解密是加密的逆过程,顺序如下:

  1. 初始轮密钥加
    使用第 10 个轮密钥与密文异或。

  2. 轮函数(重复 10 轮)

    • 逆行移位(InvShiftRows):右移恢复原始位置。
    • 逆字节代换(InvSubBytes):通过逆 S 盒还原字节。
    • 轮密钥加(AddRoundKey):与轮密钥异或(逆序使用)。
    • 逆列混淆(InvMixColumns):通过逆矩阵乘法还原列。
  3. 最终轮(省略逆列混淆)
    执行逆行移位、逆字节代换和轮密钥加。

代码实现(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} $$

注意事项

  1. 填充模式
    AES 块大小为 16 字节,明文需填充至整数倍(如 PKCS7)。

  2. 初始化向量(IV)
    CBC 模式需随机生成 IV,确保相同明文加密结果不同。

  3. 密钥安全
    密钥需通过安全方式存储或传输(如密钥派生函数)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值