當前位置:才華齋>計算機>php語言>

PHP如何使用AES加密演算法進行資料加密和解密

php語言 閱讀(9K)

在利用PHP製作專案的時候經常會使用AES加密演算法進行資料加密和解密,那麼AES加密演算法是如何進行資料加密和解密的呢?下面小編為大家解答一下,希望能幫到您!

PHP如何使用AES加密演算法進行資料加密和解密

AES加密是一種高階加密標準,AES加密採用對稱分組密碼體制,AES加密資料塊分組長度必須為128位元,金鑰長度可以是128位元、192位元、256位元中的任意一個(如果資料塊及金鑰長度不足時,會補齊)。

專案中用到了AES加密和解密資料,主要用在網路請求過程中對上傳的引數進行加密,對從後臺伺服器獲取的資料進行解密。

我們可以使用AES加密演算法將資料加密起來,然後傳送給後端,後端再將接收的'資料用約定的金鑰將資料還原,即解密,Aes演算法加密後的資料在傳輸過程中不易被破解。

在PHP中,我們需要先確保php的環境安裝好了Mcrypt擴充套件。PHP的mcrypt庫提供了對多種塊演算法的支援,支援 CBC,OFB,CFB 和 ECB 密碼模式,mcrypt庫提供了豐富的函式使用,有興趣的同學可以查閱PHP手冊。

我已經將aes加解密封裝成類,方便呼叫,在DEMO中可以看到呼叫效果。

<?php

class Aes

{

private $secrect_key;

public function __construct($secrect_key)

{

$this->secrect_key = $secrect_key;

}

// 加密

public function encrypt($str)

{

$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');

$iv = $this->createIv($cipher);

if (mcrypt_generic_init($cipher, $this->pad2Length($this->secrect_key, 16), $iv) != -1){

// PHP pads with NULL bytes if $content is not a multiple of the block size..

$cipherText = mcrypt_generic($cipher, $this->pad2Length($str, 16));

mcrypt_generic_deinit($cipher);

mcrypt_module_close($cipher);

return bin2hex($cipherText);

}

}

public function decrypt($str)

{

$padkey = $this->pad2Length($this->secrect_key, 16);

$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');

$iv = $this->createIv($td);

if (mcrypt_generic_init($td, $padkey, $iv) != -1){

$p_t = mdecrypt_generic($td, $this->hexToStr($str));

mcrypt_generic_deinit($td);

mcrypt_module_close($td);

return $this->trimEnd($p_t);

}

}

// IV自動生成

private function createIv($td)

{

$iv_size = mcrypt_enc_get_iv_size($td);

$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

return $iv;

}

// 將$text補足$padlen倍數的長度

private function pad2Length($text, $padlen)

{

$len = strlen($text)%$padlen;

$res = $text;

$span = $padlen-$len;

for ($i=0; $i<$span; $i++) {

$res .= chr($span);

}

return $res;

}

// 將解密後多餘的長度去掉(因為在加密的時候 補充長度滿足block_size的長度)

private function trimEnd($text){

$len = strlen($text);

$c = $text[$len-1];

if(ord($c) < $len){

for($i=$len-ord($c); $i<$len; $i++) {

if($text[$i] != $c){

return $text;

}

}

return substr($text, 0, $len-ord($c));

}

return $text;

}

//16進位制的轉為2進位制字串

private function hexToStr($hex){

$bin="";

for($i=0; $i<strlen($hex)-1; $i+=2) {

$bin.=chr(hexdec($hex[$i].$hex[$i+1]));

}

return $bin;

}

}

呼叫Aes類進行加密和解密方法如下:

<?php

$key = 'MYgGnQE2jDFADSFFDSEWsdD2'; //金鑰

$str = 'abc'; //要加密的字串

$aes = new Aes($key);

//加密

echo $aes->encrypt($str);

//解密

echo $aes->decrypt($str);