/** * Key expansion for Rijndael Cipher(): performs key expansion on cipher key * to generate a key schedule * * @param key cipher key byte-array (16 bytes) * @return key schedule as 2D byte-array (Nr+1 x Nb bytes) */ function KeyExpansion($key) { // generate Key Schedule from Cipher Key [§5.2] global $Rcon; // PHP needs explicit declaration to access global variables! $Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES) $Nk = count($key) / 4; // key length (in words): 4/6/8 for 128/192/256-bit keys $Nr = $Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys $w = array(); $temp = array(); for ($i = 0; $i < $Nk; $i++) { $r = array($key[4 * $i], $key[4 * $i + 1], $key[4 * $i + 2], $key[4 * $i + 3]); $w[$i] = $r; } for ($i = $Nk; $i < $Nb * ($Nr + 1); $i++) { $w[$i] = array(); for ($t = 0; $t < 4; $t++) { $temp[$t] = $w[$i - 1][$t]; } if ($i % $Nk == 0) { $temp = SubWord(RotWord($temp)); for ($t = 0; $t < 4; $t++) { $temp[$t] ^= $Rcon[$i / $Nk][$t]; } } else { if ($Nk > 6 && $i % $Nk == 4) { $temp = SubWord($temp); } } for ($t = 0; $t < 4; $t++) { $w[$i][$t] = $w[$i - $Nk][$t] ^ $temp[$t]; } } return $w; }
function KeyExpansion($key) { global $Rcon; $Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES) $Nk = count($key) / 4; // key length (in words): 4/6/8 for 128/192/256-bit keys $Nr = $Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys $w = array($Nb * ($Nr + 1)); setLength($temp, 4); for ($i = 0; $i < $Nk; $i++) { $r = array($key[4 * $i], $key[4 * $i + 1], $key[4 * $i + 2], $key[4 * $i + 3]); $w[$i] = $r; } for ($i = $Nk; $i < $Nb * ($Nr + 1); $i++) { $w[$i] = array(); for ($t = 0; $t < 4; $t++) { $temp[$t] = $w[$i - 1][$t]; } if ($i % $Nk == 0) { $temp = SubWord(RotWord($temp)); for ($t = 0; $t < 4; $t++) { $temp[$t] ^= $Rcon[$i / $Nk][$t]; } } elseif ($Nk > 6 && $i % $Nk == 4) { $temp = SubWord($temp); } for ($t = 0; $t < 4; $t++) { $w[$i][$t] = $w[$i - $Nk][$t] ^ $temp[$t]; } } return $w; }