📄 aes.cpp
字号:
KeyExpansion(CipherKey,ExKey);
//Initial Round
for (i=0;i<Nb*4;i++)
*(buffer+i) ^= *(ExKey+i);
//Rounds
for (i=1;i<Nr;i++)
Round(ExKey+4*Nb*i);
//Final Round
FinalRound(ExKey+4*Nb*Nr);
return 0;
}
int AES::Decrypt(unsigned char* State, int bSize, unsigned char* CipherKey, int kSize)
{
int i = 0;
if (State == NULL || CipherKey == NULL)
return 1;
if (bSize != 128 && bSize != 192 && bSize != 256)
return 2;
if (kSize != 128 && kSize != 192 && kSize != 256)
return 3;
buffer = State;
Nb = bSize / 32;
Nk = kSize / 32;
Nr = RoundT[3*(Nk/2-2)+(Nb/2-2)];
if(ExKey != NULL)
{
delete ExKey;
ExKey = NULL;
}
ExKey = new unsigned char[4*(Nb*(Nr+1))];
I_KeyExpansion(CipherKey,ExKey);
//Add Round Key
for (i=0;i<Nb*4;i++)
*(buffer+i) ^= *(ExKey+4*Nb*Nr+i);
//Rounds
for (i=Nr-1;i>0;i--)
I_Round(ExKey+4*Nb*i);
//Final Round
I_FinalRound(ExKey);
return 0;
}
int AES::KeyExpansion(unsigned char* Key, unsigned char*& EKey)
{
int i= 0;
unsigned char* pt=EKey;
unsigned char* pt2 = NULL;
unsigned char temp[4];
if(Key==NULL || EKey==NULL)
return 1;
for (i=0;i<Nk;i++)
{
*pt = *(Key+(4*i));
*(pt+1) = *(Key+(4*i+1));
*(pt+2) = *(Key+(4*i+2));
*(pt+3) = *(Key+(4*i+3));
pt += 4;
}//end for(i)
for (i=Nk;i<Nb*(Nr+1);i++)
{
pt2 = pt - 4;
memcpy(temp,pt2,4);
if (i % Nk == 0)
{
unsigned char t;
t = temp[0];
temp[0] = temp[1];
temp[1] = temp[2];
temp[2] = temp[3];
temp[3] = t;
temp[0] = SBoxT[temp[0]];
temp[1] = SBoxT[temp[1]];
temp[2] = SBoxT[temp[2]];
temp[3] = SBoxT[temp[3]];
temp[0] ^= RconT[i/Nk];
temp[1] ^= 0;
temp[2] ^= 0;
temp[3] ^= 0;
}//end if
else if (Nk > 6 && i % Nk == 4)
{
temp[0] = SBoxT[temp[0]];
temp[1] = SBoxT[temp[1]];
temp[2] = SBoxT[temp[2]];
temp[3] = SBoxT[temp[3]];
}//end else if
pt2 = pt - 4*Nk;
*pt = *(pt2) ^ temp[0];
*(pt+1) = *(pt2+1) ^ temp[1];
*(pt+2) = *(pt2+2) ^ temp[2];
*(pt+3) = *(pt2+3) ^ temp[3];
pt += 4;
}//end for(i)
return 0;
}
int AES::I_KeyExpansion(unsigned char* Key, unsigned char*& EKey)
{
int i= 0;
unsigned char* temp;
if(Key==NULL || EKey==NULL)
return 1;
KeyExpansion(Key,EKey);
for (i=1;i<Nr;i++)
{
temp = EKey+4*Nb*i;
InvMixColumn((temp));
}
return 0;
}
void AES::ShiftRow()
{
unsigned char c1,c2,c3,t1[4],t2[4],t3[4],i;
c1 = ShiftT[3*(Nb/2-2)];
c2 = ShiftT[3*(Nb/2-2)+1];
c3 = ShiftT[3*(Nb/2-2)+2];
for (i=0;i<4;i++)
{
t1[i] = *(buffer+(4*i)+1);
t2[i] = *(buffer+(4*i)+2);
t3[i] = *(buffer+(4*i)+3);
}
for(i=0;i<Nb;i++)
{
*(buffer+4*i+1) = *(buffer+4*((i+c1)%Nb)+1);
*(buffer+4*i+2) = *(buffer+4*((i+c2)%Nb)+2);
*(buffer+4*i+3) = *(buffer+4*((i+c3)%Nb)+3);
}
for(i=c1;i>=1;i--)
*(buffer+4*(Nb-i)+1) = t1[c1-i];
for(i=c2;i>=1;i--)
*(buffer+4*(Nb-i)+2) = t2[c2-i];
for(i=c3;i>=1;i--)
*(buffer+4*(Nb-i)+3) = t3[c3-i];
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -