void subBytes(unsigned char state[4][4], unsigned char S[16][16]) { int row = 0, col = 0; for(row=0; row<4; row++) for(col=0; col<4; col++) state[row][col] = subByte(state[row][col], S); }
void genKey(const unsigned char* pIn, unsigned char* pOut, int round) { if (round==0) return; int i; /****calculate ti ****/ unsigned char w3_r[4], t[4]; rotateWord(&pIn[12], w3_r, 4, -1); for (i=0; i<4; i++) subByte(&w3_r[i]); for (i=0; i<4; i++) t[i] = w3_r[i]^RoundConstant[i][round-1]; /*********************/ printf("t: %x %x %x %x\n", t[0], t[1], t[2], t[3]); for (i=0; i<4; i++) { pOut[0+i] = pIn[0+i]^t[i]; pOut[4+i] = pIn[0+i]^pOut[0+i]; pOut[8+i] = pIn[0+i]^pOut[4+i]; pOut[12+i] = pIn[0+i]^pOut[8+i]; } }
unsigned int subWord(unsigned int word, unsigned char S[16][16]) { unsigned int answer = 0; int i=0; unsigned char byte = 0; unsigned int mask = (unsigned int)255 << 24; for(i=0; i<4; i++) //process a byte at a time { byte = (word & mask) >> ((3-i)*8); //get 1 byte from word byte = subByte(byte, S); //find substitution for that byte answer = answer << 8; //add substituted byte to answer answer = (answer | byte); mask = mask >> 8; //shift mask to next 8 bits } return answer; }
int main () { int i,j; unsigned char state[4][4] = {{0x32,0x88,0x31,0xE0},{0x43,0x5A,0x31,0x37},{0xF6,0x30,0x98,0x07},{0xa8,0x8D,0xA2,0x34}}; unsigned char key[4][4]={{0x2B,0x28,0xAB,0x09},{0x7E,0xAE,0xF7,0xCF},{0x15,0xD2,0x15,0x4F},{0x16,0xA6,0x88,0x3C}}; unsigned char expan_key[4][44]; unsigned char temp[4][4]; //============1. Read user text into matrix================= //=== print(state); printf("\n KEY IN HEX \n"); print(key); printf("\n"); printf("\n"); key_generate(key,expan_key); printf("\n"); printf("\n"); //=================2. Add round key Correct ================ Add_key(state,key); printf("\n AFTER ADDING ROUND KEY \n"); print(state); int start=4; int loop; unsigned char temp_key[4][4]; //=================3. n round ================ for(loop=1;loop<11;loop++) { printf("\n State %d \n",loop); print(state); for(i=0;i<4;i++) { for(j=0;j<4;j++) { temp_key[j][i]=expan_key[j][loop*start+i]; } } printf("\n key %d \n",loop); print(temp_key); //=================3.a. SubByte ================ subByte(state); printf("\n AFTER SubByte\n"); print(state); printf("\n"); //=================3.b. Shift raw Correct ================ shiftRaw(state); printf("\n AFTER shift raw \n"); print(state); printf("\n"); //=================3.c. mix Column Correct ================ if(loop!=10) { mixcolumn(state,temp); printf("\n AFTER MIX COLUMN \n"); for(j=0;j<4;j++) { for (i=0;i<4;i++) { state[j][i]=temp[j][i]; } } } print(state); //=================3.d. Add round key ================ Add_key(state,temp_key); printf("\n AFTER ADDING ROUND KEY %d\n",loop); print(state); printf("\n"); } return 0; }