PHP实现实现AES256加密算法实例加密算法实例
主要介绍了PHP实现AES256加密算法,包括了对应的类文件及演示demo实例,并附带另一个PHP mcrypt加密实
例供大家参考借鉴,需要的朋友可以参考下
本文实例讲述了PHP实现AES256加密算法的方法,是较为常见的一种加密算法。分享给大家供大家参考。具体如下:
aes.class.php文件如下:
<?php
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* AES implementation in PHP (c) Chris Veness 2005-2011. Right of free use is granted for all */
/* commercial or non-commercial use under CC-BY licence. No warranty of any form is offered. */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
class Aes {
/**
* AES Cipher function: encrypt 'input' with Rijndael algorithm
*
* @param input message as byte-array (16 bytes)
* @param w key schedule as 2D byte-array (Nr+1 x Nb bytes) -
* generated from the cipher key by keyExpansion()
* @return ciphertext as byte-array (16 bytes)
*/
public static function cipher($input, $w) { // main cipher function [§5.1]
$Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
$Nr = count($w)/$Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
$state = array(); // initialise 4xNb byte-array 'state' with input [§3.4]
for ($i=0; $i<4*$Nb; $i++) $state[$i%4][floor($i/4)] = $input[$i];
$state = self::addRoundKey($state, $w, 0, $Nb);
for ($round=1; $round<$Nr; $round++) { // apply Nr rounds
$state = self::subBytes($state, $Nb);
$state = self::shiftRows($state, $Nb);
$state = self::mixColumns($state, $Nb);
$state = self::addRoundKey($state, $w, $round, $Nb);
}
$state = self::subBytes($state, $Nb);
$state = self::shiftRows($state, $Nb);
$state = self::addRoundKey($state, $w, $Nr, $Nb);
$output = array(4*$Nb); // convert state to 1-d array before returning [§3.4]
for ($i=0; $i<4*$Nb; $i++) $output[$i] = $state[$i%4][floor($i/4)];
return $output;
}
private static function addRoundKey($state, $w, $rnd, $Nb) { // xor Round Key into state S [§5.1.4]
for ($r=0; $r<4; $r++) {
for ($c=0; $c<$Nb; $c++) $state[$r][$c] ^= $w[$rnd*4+$c][$r];
}
return $state;
}
private static function subBytes($s, $Nb) { // apply SBox to state S [§5.1.1]
for ($r=0; $r<4; $r++) {
for ($c=0; $c<$Nb; $c++) $s[$r][$c] = self::$sBox[$s[$r][$c]];
}
return $s;
}
private static function shiftRows($s, $Nb) { // shift row r of state S left by r bytes [§5.1.2]
$t = array(4);
for ($r=1; $r<4; $r++) {
for ($c=0; $c<4; $c++) $t[$c] = $s[$r][($c+$r)%$Nb]; // shift into temp copy
for ($c=0; $c<4; $c++) $s[$r][$c] = $t[$c]; // and copy back
} // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
return $s; // see fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf
}
private static function mixColumns($s, $Nb) { // combine bytes of each col of state S [§5.1.3]
for ($c=0; $c<4; $c++) {
$a = array(4); // 'a' is a copy of the current column from 's'
$b = array(4); // 'b' is a•{02} in GF(2^8)