void AESInit(AESInfo_t *aesInfoP) { unsigned char i; unsigned char *pExpandKey;//扩展密钥 unsigned char Rcon[4] = {0x01, 0x00, 0x00, 0x00}; switch (aesInfoP->type) { case AES128: aesInfoP->Nr = 10; aesInfoP->Nk = 16; break; case AES192: aesInfoP->Nr = 12; aesInfoP->Nk = 24; break; case AES256: aesInfoP->Nr = 14; aesInfoP->Nk = 32; break; default: aesInfoP->Nr = 10; aesInfoP->Nk = 16; break; } //拓展密匙 memcpy(aesInfoP->expandKey, aesInfoP->key, 4 * aesInfoP->Nk);//第一个是原始密匙, pExpandKey = &aesInfoP->expandKey[4*aesInfoP->Nk]; //拓展密匙AES128:10个、AES192:12个、AES256:14个 for (i = aesInfoP->Nk; i < Nb*(aesInfoP->Nr + 1); pExpandKey += 4, i++) { memcpy(pExpandKey, pExpandKey - 4, 4); if (0 == i % aesInfoP->Nk) { RShiftWord(pExpandKey); SubstituteBytes(pExpandKey, 4, SBox); XorBytes(pExpandKey, Rcon, 4); Rcon[0] = GfMultBy02(Rcon[0]); } else if (6 < aesInfoP->Nk && i % aesInfoP->Nk == Nb) { SubstituteBytes(pExpandKey, 4, SBox); } XorBytes(pExpandKey, pExpandKey - 4 * aesInfoP->Nk, 4); } } 解释每段代码的意思
时间: 2024-02-14 07:10:51 浏览: 98
QString含汉字时,完美转char*和unsigned char*
这段代码是AES加密算法的初始化函数,主要作用是填充AESInfo_t结构体的各项参数,并生成扩展密钥。具体解释如下:
```c++
void AESInit(AESInfo_t *aesInfoP) {
unsigned char i;
unsigned char *pExpandKey; // 指向扩展密钥的指针
unsigned char Rcon[4] = {0x01, 0x00, 0x00, 0x00}; // 轮常数数组
switch (aesInfoP->type) {
case AES128:
aesInfoP->Nr = 10; // 轮数
aesInfoP->Nk = 16; // 密钥长度(字节)
break;
case AES192:
aesInfoP->Nr = 12;
aesInfoP->Nk = 24;
break;
case AES256:
aesInfoP->Nr = 14;
aesInfoP->Nk = 32;
break;
default:
aesInfoP->Nr = 10;
aesInfoP->Nk = 16;
break;
}
// 拓展密匙
memcpy(aesInfoP->expandKey, aesInfoP->key, 4 * aesInfoP->Nk); // 复制原始密钥到扩展密钥的前Nk个字节
pExpandKey = &aesInfoP->expandKey[4*aesInfoP->Nk]; // 指向扩展密钥的第Nk个字节(即原始密钥之后)
for (i = aesInfoP->Nk; i < Nb*(aesInfoP->Nr + 1); pExpandKey += 4, i++) {
memcpy(pExpandKey, pExpandKey - 4, 4); // 复制前一个4字节到当前位置
if (0 == i % aesInfoP->Nk) { // 每Nk个字节进行一次特殊处理
RShiftWord(pExpandKey); // 字节循环左移一位
SubstituteBytes(pExpandKey, 4, SBox); // 字节替换
XorBytes(pExpandKey, Rcon, 4); // 字节异或轮常数
Rcon[0] = GfMultBy02(Rcon[0]); // 计算下一个轮常数
} else if (6 < aesInfoP->Nk && i % aesInfoP->Nk == Nb) { // 对于AES-256而言,每4*Nk个字节进行一次特殊处理
SubstituteBytes(pExpandKey, 4, SBox); // 字节替换
}
XorBytes(pExpandKey, pExpandKey - 4 * aesInfoP->Nk, 4); // 与前Nk个字节异或
}
}
```
上述代码中,Nb表示列数,对于AES而言,Nb=4。而SBox和GfMultBy02是AES算法中使用的两个表格和一个算法,用于字节替换和轮常数计算。具体实现细节可以参考AES算法的原理和流程。
阅读全文