PHP-AES标准Rijndael算法的介绍与实现

1.前言

AES( Advanced Encryption Standard )高级加密标准,又称 Rijndael加密法。它是由 美国国家标准与技术研究院 (NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准 。 该算法由比利时密码学家Joan Daemen和Vincent Rijmen所设计,结合两位作者的名字 而命名。AES标准支持固定分组128位,密钥长度可以是128位、192位、256位。

2.工作模式

我们知道,对明文进行加密的过程中,如果明文超过了分组大小,那么就需要进行切割处理,而AES提供给我们多种工作模式,分别是:ECB(电子密码本)、CBC(密文分组链接)、CFB(密文反馈)、OFB(输出反馈)、CTR(计数器),而我们今天只争对128位的明文进行加密解密处理,分组工作模式不在我们今天讨论的范畴。

3.介绍

3.1状态矩阵

AES算法中的状态矩阵是垂直排列的,如下图所示。

明文第一步需要转换成状态矩阵,而初始密钥在进行扩展密钥之前也需要转化成状态矩阵。在对密文进行解密时,最后需要将状态矩阵还原为明文矩阵。

3.2密钥扩展

密钥扩展会生成44组4个字节的轮密钥,每16个字节为1轮密钥,在进行轮密钥加的时候,需要将处理过的明文状态矩阵根据每轮的密钥进行加密处理。下面我们来看一个例子,假如初始密钥16位为: abcdefghijklmnop ,那么它的初始轮密钥如下所示:

接下来还需要生成40组W,计算公式如下:

W[n] = W[n-4] xor W[n-1] (if n%4 !== 0)

W[n] = W[n-4] xor 字节替换(循环左移1位(W[n-1])) xor 轮常量[(n/4) – 1] (if n%4 === 0)

循环左移:如0x12345678 => 0x34567812

轮常量是固定的数组如下所示:

0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000

3.3字节替换

字节替换,是利用AES提供的S盒来进行替换的,其中高4位代表行数,而低4位则代表列数。在解密时,也用相同的规则在S逆盒中进行替换还原。

3.4行移位

行移位第0行无需移动,第i行则向左循环移动i次,解密时则向右循环移动i次。下面时一个例子:

3.5列混合

列混合的操作是基于有限域伽罗华域的计算,上一篇文章中我们已经介绍过了该计算方式: https://www.pitmanhuang.com/archives/474

在进行列混合操作时,将状态矩阵与固定的常量矩阵进行有限域的乘积,将结果异或得出列混合后的值。其中加密和解密的常量值数组是不同的,它们分别为:

$constArray = [0x02, 0x03, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x01, 0x01, 0x02, 0x03, 0x03, 0x01, 0x01, 0x02];
$constArrayReverse = [0x0E, 0x0B, 0x0D, 0x09, 0x09, 0x0E, 0x0B, 0x0D, 0x0D, 0x09, 0x0E, 0x0B, 0x0B, 0x0D, 0x09, 0x0E];

4.代码示例

<?php
/**
 * 伽罗华域乘积
 * @param $a
 * @param int $b
 * @return int|mixed
 */
function aes_multi($a, $b = 0)
{
    if ($a >= 2 ** 8 || 2 ** 8 <= $b) {
        exit('只支持GF(2^8)域的计算');
    }
    $binMulti = [];
    $result = 0;
    for ($i = 0; $i < 8; $i++) {
        $a = ($a & 0x100) ? (($a & 0xFF) ^ 0x1B) : $a;
        $binMulti[] = $a;
        $a = $a << 1;
    }

    $binString = str_pad(base_convert($b, 10, 2), 8, 0, STR_PAD_LEFT);

    for ($i = 0; $i < 8; $i++) {
        if ($binString{$i} === '1') {
            $pos = strlen(substr($binString, $i)) - 1;
            $result ^= $binMulti[$pos];
        }
    }
    return $result;
}

$rcon = [
    0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
    0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000
];

$constArray = [0x02, 0x03, 0x01, 0x01, 0x01, 0x02, 0x03, 0x01, 0x01, 0x01, 0x02, 0x03, 0x03, 0x01, 0x01, 0x02];
$constArrayReverse = [0x0E, 0x0B, 0x0D, 0x09, 0x09, 0x0E, 0x0B, 0x0D, 0x0D, 0x09, 0x0E, 0x0B, 0x0B, 0x0D, 0x09, 0x0E];
//S盒
$s = [
    0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
    0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
    0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
    0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
    0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
    0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
    0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
    0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
    0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
    0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
    0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
    0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
    0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
    0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
    0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
    0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
];

//逆S盒
$ss = [
    0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
    0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
    0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
    0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
    0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
    0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
    0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
    0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
    0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
    0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
    0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
    0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
    0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
    0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
    0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
    0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
];

/**
 * 密钥扩展
 * @param $keys
 */
function aes_key_extend($keys)
{
    $w = [];
    global $rcon;
    for ($i = 0; $i < strlen($keys); $i += 4) {
        $first = ord($keys{$i}) << 24;
        $second = ord($keys{$i + 1}) << 16;
        $third = ord($keys{$i + 2}) << 8;
        $fourth = ord($keys{$i + 3});
        $w[] = ($first | $second | $third | $fourth);
    }

    for ($n = 4; $n <= 43; $n++) {
        if ($n % 4 !== 0) {
            $w[$n] = $w[$n - 4] ^ $w[$n - 1];
        } else {
            $mix = (($w[$n - 1] & 0xFF000000) >> 24) | (($w[$n - 1] & 0x00FFFFFF) << 8);
            $mix = subBytes($mix);
            $w[$n] = (($w[$n - 4] ^ $mix ^ $rcon[($n / 4) - 1]));
        }
    }

    return $w;
}

/**
 * 字节替换,将32位key按照S盒替换,高4位为行数,低4位为列数
 * @param $keys
 * @return int
 */
function subBytes($keys)
{

    $first = getSValue(((((0xFF000000 & $keys) >> 24) & 0xF0) >> 4) * 16 + (((0xFF000000 & $keys) >> 24) & 0xF)) << 24;
    $second = getSValue(((((0x00FF0000 & $keys) >> 16) & 0xF0) >> 4) * 16 + (((0x00FF0000 & $keys) >> 16) & 0xF)) << 16;
    $third = getSValue(((((0x0000FF00 & $keys) >> 8) & 0xF0) >> 4) * 16 + (((0x0000FF00 & $keys) >> 8) & 0xF)) << 8;
    $fourth = getSValue((((0x000000FF & $keys) & 0xF0) >> 4) * 16 + ((0x000000FF & $keys) & 0xF));

    return $first | $second | $third | $fourth;
}

/**
 * 将8位字节按S盒规则替换
 * @param $key
 * @param $type
 */
function subByte($key, $type = 1)
{
    $row = ($key & 0xF0) >> 4;
    $col = ($key & 0xF);

    return getSValue($row * 16 + $col, $type);
}

/**
 * 将16个字节转成4*4的矩阵,并用S盒替换
 * @param $plainText
 * @return array
 */
function to4x4Array($plainText)
{
    $states = [];
    for ($i = 0; $i < 4; $i++) {
        for ($j = 0; $j < 4; $j++) {
            $states[] = ord($plainText{($j === 0 ? $i : 4 * $j + $i)});
        }
    }
    return $states;
}

function getSValue($key, $type = 1)
{
    global $s, $ss;
    return $type === 1 ? $s[$key] : $ss[$key];
}

/**
 * 行移位
 * 第0行不变,第i行左移i位 i>0
 * @param &$arr
 * @param $type
 */
function shiftRows(&$arr, $type = 1)
{
    for ($i = 1; $i < 4; $i++) {
        $index = 4 * $i;
        $temp = $arr;
        for ($j = 0; $j < 4; $j++) {
            $key = ($index + $i + $j) > (4 * $i + 3) ? 4 * $i - 1 + ($index + $i + $j - 4 * $i - 3) : $index + $j + $i;
            if ($type === 2) {
                $key = ($index + $j - $i < 4 * $i) ? 4 * ($i+1) - (4 * $i - ($index + $j - $i)) : $index + $j - $i;
            }
            $arr[$index + $j] = $temp[$key];
        }
    }
}

/**
 * 列混合
 * @param $arr
 * @param $type
 */
function mixColumns(&$arr, $type = 1)
{
    global $constArray, $constArrayReverse;
    $mixStates = [];
    for ($i = 0; $i < 16; $i++) {
        $result = 0;
        for ($j = 0; $j < 4; $j++) {
            $result ^= aes_multi($arr[4 * $j + $i % 4], $type === 1 ? $constArray[4 * (floor($i / 4)) + $j] : $constArrayReverse[4 * (floor($i / 4)) + $j]);
        }
        $mixStates[$i] = $result;
    }
    $arr = $mixStates;
}

function roundAddKey($states, $keys, $round = 0)
{
    static $result = [];

    $tempStates = $states;
    if ($round > 10) {
        return implode('', array_map(function ($n) {
            return sprintf("%02X", $n);
        }, $tempStates));
    }

    if ($round !== 0) {
        $tempStates = [];
        foreach ($states as $k => $val) {
            $tempStates[] = subByte($val);

        }
        shiftRows($tempStates);
        if ($round !== 10) { //最后一轮无需列混合
            mixColumns($tempStates);
        }
    }

    foreach ($tempStates as $k2 => $val2) {
        $result[$round][] = $val2 ^ $keys[$round][$k2];
    }

    return roundAddKey($result[$round], $keys, ++$round);
}

function roundReverseAddKey($states, $keys, $round = 10)
{
    static $result = [];
    $tempStates = [];
    foreach ($states as $k => $val) {
        $tempStates[] = $val ^ $keys[$round][$k];
    }
    if ($round === 0) {
        $result[$round] = $tempStates;
        $newest = [];
        for($i = 0; $i < 4; $i++) {
            for($j = 0; $j < 4; $j++) {
                $newest[] = $tempStates[4*$j + $i];
            }
        }
        return implode('', array_map(function ($n) {
            return chr($n);
        }, $newest));
    } else if ($round !== 10) {
        mixColumns($tempStates, 2);
    }

    shiftRows($tempStates, 2);
    foreach ($tempStates as $k => $state) {
        $result[$round][] = subByte($state, 2);
    }

    return roundReverseAddKey($result[$round], $keys, --$round);
}

function addRoundKey($states, $extendKeys, $type=1)
{
    $new4x4Keys = [];
    $cloneStates = $states;
    $roundKeys = array_chunk($extendKeys, 4);
    foreach ($roundKeys as $k => $keys) {
        foreach ($keys as $index => $key) {
            $temp = [];
            $temp[] = ($key & 0xFF000000) >> 24;
            $temp[] = ($key & 0x00FF0000) >> 16;
            $temp[] = ($key & 0x0000FF00) >> 8;
            $temp[] = ($key & 0xFF);
            for ($row = 0; $row < 4; $row++) {
                $new4x4Keys[$k][$row * 4 + $index] = $temp[$row];
            }
            ksort($new4x4Keys[$k]);
        }
    }
    return $type === 1 ?
        roundAddKey($cloneStates, $new4x4Keys, 0) :
        roundReverseAddKey($cloneStates, $new4x4Keys, 10);
}

function php_aes_encrypt($key, $plain)
{
    return addRoundKey(to4x4Array($plain), aes_key_extend($key));
}

function php_aes_decrypt($key, $plain)
{
    $states = [];
    for($i = 0; $i < 32; $i+=2) {
        $states[] =hexdec($plain{$i} . $plain{$i+1});
    }
    return addRoundKey($states, aes_key_extend($key), 2);
}

$p = 'abcdefghijklmnop';
$k = '1234567890abcdef';
$plain = php_aes_encrypt($k, $p);
var_dump($plain);
var_dump(php_aes_decrypt($k, $plain));



5.参考地址

官方文档

https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf

《密码编码学与网络安全原理与实践》

百度百科

https://baike.baidu.com/item/%E9%AB%98%E7%BA%A7%E5%8A%A0%E5%AF%86%E6%A0%87%E5%87%86/468774?fromtitle=aes&fromid=5903&fr=aladdin

网络博客

http://blog.dynox.cn/?p=1562&cpage=1
如无特殊说明,文章均为本站原创,转载请注明出处。如发现有什么不对的地方,希望得到您的指点。

发表评论

电子邮件地址不会被公开。 必填项已用*标注