PHP加密擴展庫—Mcrypt擴展庫
概要:
php從7.0升級到7.1廢棄了一個擴展,即mcrypt擴展,雖然安裝上擴展也能正常使用,但是會發出警告,告訴我們mcrypt相關方法已經被廢棄,到了7.2,已經被移除,因此不建議繼續使用,
來源:
在使用微信,淘寶第三方開發檔案的時候,很多地方還是沿用以前的加密方法,這個時候我們需要找到替換的方法,openssl就是不錯的選擇,這就需要我們清楚mcrypt和openssl之間的差異,以便保證資料加解密的一致性,
詳解mcrypt和openssl來實作AES-128/192/256-CBC加解密
1. 條件約束
之前PHP5上常使用的mcrypt庫在PHP7.1+上已經被移除,故我們采用openssl對資料進行加解密,
加密方式采用DES-EDE-CBC方式,
密鑰填充方式為:采用24位密鑰,先將key進行MD5校驗取值,得出16位字串,再取key MD5校驗值前8位追加到先前的取值后面,由此組裝出24位的密鑰,
2. 代碼分享
<?php class DesEdgCbc { private $cipher, $key, $iv; public function __construct($cipher, $key, $iv){ $this->cipher = $cipher; $this->key = $this->getFormatKey($key); $this->iv = $iv; } /** * [加密] * @param [type] $msg [description] * @return [string] [description] */ public function encrypt($msg){ $des = @openssl_encrypt($msg, $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv); return base64_encode($des); } /** * 解密 * @param [type] $msg [description] * @return [string] [description] */ public function decrypt($msg){ return @openssl_decrypt(base64_decode($msg), $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv); } public function getFormatKey($skey){ $md5Value = md5($skey); $md5ValueLen = strlen($md5Value); $key = $md5Value.substr($md5ValueLen, 0, $md5ValueLen/2); return hex2bin($key);//把十六進制值轉換為 ASCII 字符 } } $cipher = 'DES-EDE-CBC'; $msg = 'hello, cyy'; $key = '123456789'; $iv = "\x00\x00\x00\x00\x00\x00\x00\x00"; $des = new DesEdgCbc($cipher, $key, $iv); //加密 $msg = $des->encrypt($msg); echo '加密后:'.$msg.'<br/>'; //解密 $src = $des->decrypt($msg); echo '解密后:'.$src.'<br/>';
結果為:

3. 一點說明
可以根據實際情況調整加密方式、key的填充方式、及iv向量來滿足不同的需求,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/40955.html
標籤:PHP
上一篇:PHP-FPM 開啟慢日志記錄
