This commit is contained in:
2026-05-21 08:07:16 +08:00
parent 90908cf018
commit 84d8874a38
32 changed files with 271 additions and 27 deletions
+13
View File
@@ -34,6 +34,7 @@ static const uint8_t Rcon[11] = {
#define getSBoxValue(num) (sbox[(num)])
// 密钥扩展
/* 函数作用:根据 AES-128 主密钥生成每轮加密使用的轮密钥。 */
static void KeyExpansion(uint8_t* RoundKey, const uint8_t* Key)
{
unsigned i, j, k;
@@ -82,6 +83,7 @@ static void KeyExpansion(uint8_t* RoundKey, const uint8_t* Key)
}
// AddRoundKey
/* 函数作用:将当前状态矩阵与指定轮密钥进行异或。 */
static void AddRoundKey(uint8_t round, uint8_t* state, const uint8_t* RoundKey)
{
uint8_t i, j;
@@ -93,6 +95,7 @@ static void AddRoundKey(uint8_t round, uint8_t* state, const uint8_t* RoundKey)
}
// SubBytes
/* 函数作用:使用 AES S 盒对状态矩阵进行字节替换。 */
static void SubBytes(uint8_t* state)
{
uint8_t i;
@@ -102,6 +105,7 @@ static void SubBytes(uint8_t* state)
}
// ShiftRows
/* 函数作用:执行 AES 加密流程中的行移位变换。 */
static void ShiftRows(uint8_t* state)
{
uint8_t temp;
@@ -130,12 +134,14 @@ static void ShiftRows(uint8_t* state)
}
// xtime (用于MixColumns)
/* 函数作用:在 AES 有限域中执行乘以 2 的运算。 */
static uint8_t xtime(uint8_t x)
{
return ((x << 1) ^ (((x >> 7) & 1) * 0x1b));
}
// MixColumns
/* 函数作用:执行 AES 加密流程中的列混淆变换。 */
static void MixColumns(uint8_t* state)
{
uint8_t i;
@@ -164,6 +170,7 @@ static void MixColumns(uint8_t* state)
}
// Cipher - AES加密核心
/* 函数作用:对 16 字节状态块执行完整 AES 加密。 */
static void Cipher(uint8_t* state, const uint8_t* RoundKey)
{
uint8_t round = 0;
@@ -187,22 +194,26 @@ static void Cipher(uint8_t* state, const uint8_t* RoundKey)
// ========== 公开API函数 ==========
/* 函数作用:初始化 AES 上下文并生成轮密钥。 */
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key)
{
KeyExpansion(ctx->RoundKey, key);
}
/* 函数作用:初始化 AES 上下文并设置 CBC 模式 IV。 */
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv)
{
KeyExpansion(ctx->RoundKey, key);
memcpy(ctx->Iv, iv, AES_BLOCKLEN);
}
/* 函数作用:对单个 16 字节数据块执行 AES-ECB 加密。 */
void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf)
{
Cipher(buf, ctx->RoundKey);
}
/* 函数作用:使用 AES-CBC 模式加密指定长度的数据缓冲区。 */
void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length)
{
size_t i;
@@ -223,12 +234,14 @@ void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length)
}
// STM32端不需要解密功能
/* 函数作用:对单个 16 字节数据块执行 AES-ECB 解密。 */
void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf)
{
(void)ctx;
(void)buf;
}
/* 函数作用:使用 AES-CBC 模式解密指定长度的数据缓冲区。 */
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length)
{
(void)ctx;