糯米文學吧

位置:首頁 > 計算機 > php語言

PHP如何使用AES加密算法進行數據加密和解密

php語言8.62K

在利用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);