AES.docx
《AES.docx》由会员分享,可在线阅读,更多相关《AES.docx(13页珍藏版)》请在冰豆网上搜索。
![AES.docx](https://file1.bdocx.com/fileroot1/2022-12/14/6ea0b521-9b2a-415e-8cf6-4100c49e0c51/6ea0b521-9b2a-415e-8cf6-4100c49e0c511.gif)
AES
/*RijndaelBlockCipher-rijndael.c
EditedbyJianqinZhou28stApril2004
WrittenbyMikeScott21stApril1999
mike@compapp.dcu.ie
AnalternativefasterversionisimplementedinMIRACL
ftp:
//puting.dcu.ie/pub/crypto/miracl.zip
Copyright(c)1999MikeScott
Simplycompileandrun,e.g.
cl/O2rijndael.c(MicrosoftC)
bcc32/O2rijndael.c(BorlandC)
gcc-O2rijndael.c-orijndael(GnuC)
CompilesandrunsfineasaC++programalso.
Seerijndaeldocumentation.Thecodefollowsthedocumentationasclosely
aspossible,andwherepossibleusesthesamefunctionandvariablenames.
Permissionforfreedirectorderivativeuseisgrantedsubject
tocompliancewithanyconditionsthattheoriginatorsofthe
algorithmplaceonitsexploitation.
InspirationfromBrianGladman'simplementationisacknowledged.
Writtenforclarity,ratherthanspeed.
Assumeslongis32bitquantity.
Fullimplementation.
Endianindifferent.
*/
#include
#defineBYTEunsignedchar/*8bits*/
#defineWORDunsignedlong/*32bits*/
/*rotatesxonebittotheleft*/
#defineROTL(x)(((x)>>7)|((x)<<1))
/*Rotates32-bitwordleftby1,2or3byte*/
#defineROTL8(x)(((x)<<8)|((x)>>24))
#defineROTL16(x)(((x)<<16)|((x)>>16))
#defineROTL24(x)(((x)<<24)|((x)>>8))
/*FixedData*/
staticBYTEInCo[4]={0xB,0xD,0x9,0xE};/*InverseCoefficients*/
staticBYTEfbsub[256];
staticBYTErbsub[256];
staticBYTEptab[256],ltab[256];
staticWORDftable[256];
staticWORDrtable[256];
staticWORDrco[30];
/*Parameter-dependentdata*/
intNk,Nb,Nr;
BYTEfi[24],ri[24];
WORDfkey[120];
WORDrkey[120];
staticWORDpack(BYTE*b)
{/*packbytesintoa32-bitWord*/
return((WORD)b[3]<<24)|((WORD)b[2]<<16)|((WORD)b[1]<<8)|(WORD)b[0];
}
staticvoidunpack(WORDa,BYTE*b)
{/*unpackbytesfromaword*/
b[0]=(BYTE)a;
b[1]=(BYTE)(a>>8);
b[2]=(BYTE)(a>>16);
b[3]=(BYTE)(a>>24);
}
//关于模多项式0x011b的乘10b运算
staticBYTExtime(BYTEa)
{
BYTEb;
if(a&0x80)b=0x1B;
elseb=0;
a<<=1;
a^=b;
returna;
}
staticBYTEbmul(BYTEx,BYTEy)
{/*x.y=AntiLog(Log(x)+Log(y))*/
if(x&&y)returnptab[(ltab[x]+ltab[y])%255];
elsereturn0;
}
staticWORDSubByte(WORDa)
{
BYTEb[4];
unpack(a,b);
b[0]=fbsub[b[0]];
b[1]=fbsub[b[1]];
b[2]=fbsub[b[2]];
b[3]=fbsub[b[3]];
returnpack(b);
}
staticBYTEproduct(WORDx,WORDy)
{/*dotproductoftwo4-bytearrays*/
BYTExb[4],yb[4];
unpack(x,xb);
unpack(y,yb);
returnbmul(xb[0],yb[0])^bmul(xb[1],yb[1])^bmul(xb[2],yb[2])^bmul(xb[3],yb[3]);
}
staticWORDInvMixCol(WORDx)
{/*matrixMultiplication*/
WORDy,m;
BYTEb[4];
m=pack(InCo);
b[3]=product(m,x);
m=ROTL24(m);
b[2]=product(m,x);
m=ROTL24(m);
b[1]=product(m,x);
m=ROTL24(m);
b[0]=product(m,x);
y=pack(b);
returny;
}
BYTEByteSub(BYTEx)
{
BYTEy=ptab[255-ltab[x]];/*multiplicativeinverse*/
x=y;x=ROTL(x);
y^=x;x=ROTL(x);
y^=x;x=ROTL(x);
y^=x;x=ROTL(x);
y^=x;y^=0x63;
returny;
}
voidgentables(void)
{/*generatetables*/
inti;
BYTEy,b[4];
/*use3asprimitiveroottogeneratepowerandlogtables*/
ltab[0]=0;
ptab[0]=1;ltab[1]=0;
ptab[1]=3;ltab[3]=1;
for(i=2;i<256;i++)
{
ptab[i]=ptab[i-1]^xtime(ptab[i-1]);
ltab[ptab[i]]=i;
}
/*affinetransformation:
-eachbitisxoredwithitselfshiftedonebit
仿射变换
*/
fbsub[0]=0x63;
rbsub[0x63]=0;
for(i=1;i<256;i++)
{
y=ByteSub((BYTE)i);
fbsub[i]=y;rbsub[y]=i;
}
for(i=0,y=1;i<30;i++)
{
rco[i]=y;
y=xtime(y);
}
/*calculateforwardandreversetables*/
for(i=0;i<256;i++)
{
y=fbsub[i];
b[3]=y^xtime(y);b[2]=y;
b[1]=y;b[0]=xtime(y);
ftable[i]=pack(b);
y=rbsub[i];
b[3]=bmul(InCo[0],y);b[2]=bmul(InCo[1],y);
b[1]=bmul(InCo[2],y);b[0]=bmul(InCo[3],y);
rtable[i]=pack(b);
}
}
voidstrtoHex(char*str,char*hex)
{
charch;
inti=0,by=0;
while(i<64&&*str)//themaximumkeylengthis32bytes(256bits)and
{//henceatmost64hexadecimaldigits
ch=toupper(*str++);//processahexadecimaldigit
if(ch>='0'&&ch<='9')
by=(by<<4)+ch-'0';
elseif(ch>='A'&&ch<='F')
by=(by<<4)+ch-'A'+10;
else//errorifnothexadecimal
{
printf("keymustbeinhexadecimalnotation\n");
exit(0);
}
//storeakeybyteforeachpairofhexadecimaldigits
if(i++&1)
hex[i/2-1]=by&0xff;
}
}
voidhextoStr(char*hex,char*str)
{
inti=0,by=0;
while(i<32&&*hex)//themaximumkeylengthis32bytes(256bits)and
{//henceatmost64hexadecimaldigits
by=*hex;//processahexadecimaldigit(high)
by=by>>4&0x0f;
if(by>=0&&by<=9)
*str++=by+'0';
elseif(by>=0x0A&&by<=0x0F)
*str++=by-10+'A';
by=*hex++;//processahexadecimaldigit(low)
by=by&0x0f;
if(by>=0&&by<=9)
*str++=by+'0';
elseif(by>=0x0A&&by<=0x0F)
*str++=by-10+'A';
i++;
}
}
voidgkey(intnb,intnk,char*key)
{/*blocksize=32*nbbits.Key=32*nkbits*/
/*currentlynb,bk=4,6or8*/
/*keycomesas4*Nkbytes*/
/*KeyScheduler.Createexpandedencryptionkey*/
inti,j,k,m,N;
intC1,C2,C3;
WORDCipherKey[8];
Nb=nb;Nk=nk;
/*Nrisnumberofrounds*/
if(Nb>=Nk)Nr=6+Nb;
elseNr=6+Nk;
C1=1;
if(Nb<8){C2=2;C3=3;}
else{C2=3;C3=4;}
/*pre-calculateforwardandreverseincrements*/
for(m=j=0;j{
fi[m]=(j+C1)%nb;
fi[m+1]=(j+C2)%nb;
fi[m+2]=(j+C3)%nb;
ri[m]=(nb+j-C1)%nb;
ri[m+1]=(nb+j-C2)%nb;
ri[m+2]=(nb+j-C3)%nb;
}
N=Nb*(Nr+1);
for(i=j=0;i{
CipherKey[i]=pack((BYTE*)&key[j]);
}
for(i=0;ifor(j=Nk,k=0;j{
fkey[j]=fkey[j-Nk]^SubByte(ROTL24(fkey[j-1]))^rco[k];
if(Nk<=6)
{
for(i=1;ifkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1];
}
else
{
for(i=1;i<4&&(i+j)fkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1];
if((j+4)for(i=5;ifkey[i+j]=fkey[i+j-Nk]^fkey[i+j-1];
}
}
/*nowfortheexpandeddecryptkeyinreverseorder*/
for(j=0;jfor(i=Nb;i{
k=N-Nb-i;
for(j=0;j}
for(j=N-Nb;j}
/*Thereisanobvioustime/spacetrade-offpossiblehere.*
*Insteadofjustoneftable[],Icouldhave4,theother*
*3pre-rotatedtosavetheROTL8,ROTL16andROTL24overhead*/
voidencrypt(char*buff)
{
inti,j,k,m;
WORDa[8],b[8],*x,*y,*t;
for(i=j=0;i{
a[i]=pack((BYTE*)&buff[j]);
a[i]^=fkey[i];
}
k=Nb;
x=a;y=b;
/*Statealternatesbetweenaandb*/
for(i=1;i{/*Nrisnumberofrounds.Maybeodd.*/
/*ifNbisfixed-unrollthisnext
loopandhard-codeinthevaluesoffi[]*/
for(m=j=0;j{/*dealwitheach32-bitelementoftheState*/
/*Thisisthetime-criticalbit*/
y[j]=fkey[k++]^ftable[(BYTE)x[j]]^
ROTL8(ftable[(BYTE)(x[fi[m]]>>8)])^
ROTL16(ftable[(BYTE)(x[fi[m+1]]>>16)])^
ROTL24(ftable[x[fi[m+2]]>>24]);
}
t=x;x=y;y=t;/*swappointers*/
}
/*LastRound-unrollifpossible*/
for(m=j=0;j{
y[j]=fkey[k++]^(WORD)fbsub[(BYTE)x[j]]^
ROTL8((WORD)fbsub[(BYTE)(x[fi[m]]>>8)])^
ROTL16((WORD)fbsub[(BYTE)(x[fi[m+1]]>>16)])^
ROTL24((WORD)fbsub[x[fi[m+2]]>>24]);
}
for(i=j=0;i{
unpack(y[i],(BYTE*)&buff[j]);
x[i]=y[i]=0;/*cleanupstack*/
}
return;
}
voiddecrypt(char*buff)
{
inti,j,k,m;
WORDa[8],b[8],*x,*y,*t;
for(i=j=0;i{
a[i]=pack((BYTE*)&buff[j]);
a[i]^=rkey[i];
}
k=Nb;
x=a;y=b;
/*Statealternatesbetweenaandb*/
for(i=1;i{/*Nrisnumberofrounds.Maybeodd.*/
/*ifNbisfixed-unrollthisnext
loopandhard-codeinthevaluesofri[]*/
for(m=j=0;j{/*Thisisthetime-criticalbit*/
y[j]=rkey[k++]^rtable[(BYTE)x[j]]^
ROTL8(rtable[(BYTE)(x[ri[m]]>>8)])^
ROTL16(rtable[(BYTE)(x[ri[m+1]]>>16)])^
ROTL24(rtable[x[ri[m+2]]>>24]);
}
t=x;x=y;y=t;/*swappointers*/
}
/*LastRound-unrollifpossible*/
for(m=j=0;j{
y[j]=rkey[k++]^(WORD)rbsub[(BYTE)x[j]]^
ROTL8((WORD)rbsub[(BYTE)(x[ri[m]]>>8)])^
ROTL16((WORD)rbsub[(BYTE)(x[ri[m+1]]>>16)])^
ROTL24((WORD)rbsub[x[ri[m+2]]>>24]);
}
for(i=j=0;i{
unpack(y[i],(BYTE*)&buff[j]);
x[i]=y[i]=0;/*cleanupstack*/
}
return;
}
intmain()
{/*testdriver*/
inti,nb,nk;
charstr[]="abcd1234567890123456789012345678901212345678901234567890123456789012";
charkey[32];
charblock[32];
gentables();
strtoHex(str,key);
hextoStr(key,str);//justtotestthesetwofunctions
printf("Key=");
for(i=0;i<64;i++)printf("%c",str[i]);
printf("\n");
for(i=0;i<32;i++)block[i]=i;
for(nb=4;nb<=8;nb+=2)
for(nk=4;nk<=8;nk+=2)
{
printf("\nBlockSize=%dbits,KeySize=%dbits\n",nb*32,nk*32);
gkey(nb,nk,key);
printf("Plain=");
for(i=0;iprintf("\n");
encrypt(block);
printf("Encrypt=");
for(i=0;iprintf("\n");
decrypt(block);
printf("Decrypt=");
for(i=0;iprintf("\n");
}
return0;
}