// The sub_bytes Function Substitutes the values in the // state matrix with values in an S-box. void sub_bytes() { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { state[i][j] = get_sbox_value(state[i][j]); } } }
// This function produces nb(nr+1) round keys. The round keys are used in each round to encrypt the states. void key_expansion() { int i, j; unsigned char temp[4], k; // The first round key is the key itself. for (i = 0; i < nk; i++) { round_key[i * 4] = key[i * 4]; round_key[i * 4 + 1] = key[i * 4 + 1]; round_key[i * 4 + 2] = key[i * 4 + 2]; round_key[i * 4 + 3] = key[i * 4 + 3]; } // All other round keys are found from the previous round keys. while (i < (nb * (nr + 1))) { for (j = 0; j < 4; j++) { temp[j] = round_key[(i - 1) * 4 + j]; } if (i % nk == 0) { // This function rotates the 4 bytes in a word to the left once. // [a0,a1,a2,a3] becomes [a1,a2,a3,a0] // Function RotWord() { k = temp[0]; temp[0] = temp[1]; temp[1] = temp[2]; temp[2] = temp[3]; temp[3] = k; } // SubWord() is a function that takes a four-byte input word and // applies the S-box to each of the four bytes to produce an output word. // Function Subword() { temp[0] = get_sbox_value(temp[0]); temp[1] = get_sbox_value(temp[1]); temp[2] = get_sbox_value(temp[2]); temp[3] = get_sbox_value(temp[3]); } temp[0] = temp[0] ^ rcon[i / nk]; } else if (nk > 6 && i % nk == 4) { // Function Subword() { temp[0] = get_sbox_value(temp[0]); temp[1] = get_sbox_value(temp[1]); temp[2] = get_sbox_value(temp[2]); temp[3] = get_sbox_value(temp[3]); } } round_key[i * 4 + 0] = round_key[(i - nk) * 4 + 0] ^ temp[0]; round_key[i * 4 + 1] = round_key[(i - nk) * 4 + 1] ^ temp[1]; round_key[i * 4 + 2] = round_key[(i - nk) * 4 + 2] ^ temp[2]; round_key[i * 4 + 3] = round_key[(i - nk) * 4 + 3] ^ temp[3]; i++; } }