php openssl des ecb,PHP7 OpenSSL DES-EDE-CBC加解密
1. 條件約束
之前PHP5上常使用的mcrypt庫(kù)在PHP7.1+上已經(jīng)被移除,故我們采用openssl對(duì)數(shù)據(jù)進(jìn)行加解密。
加密方式采用DES-EDE-CBC方式。
密鑰填充方式為:采用24位密鑰,先將key進(jìn)行MD5校驗(yàn)取值,得出16位字串,再取key MD5校驗(yàn)值前8位追加到先前的取值后面。由此組裝出24位的密鑰。
2. 代碼分享<?phpclass DesEdeCbc {private $cipher, $key, $iv;/** * DesEdeCbc constructor. * @param $cipher * @param $key * @param $iv */public function __construct($cipher, $key, $iv) {$this->cipher = $cipher;$this->key= $this->getFormatKey($key);$this->iv = $iv;}/** * @func 加密 * @param $msg * @return string */public function encrypt($msg) {$des = @openssl_encrypt($msg, $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);return base64_encode($des);}/** * @func 解密 * @param $msg * @return string */public function decrypt($msg) {return @openssl_decrypt(base64_decode($msg), $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);}/** * @func 生成24位長(zhǎng)度的key * @param $skey * @return bool|string */private function getFormatKey($skey) {$md5Value= md5($skey);$md5ValueLen = strlen($md5Value);$key = $md5Value . substr($md5Value, 0, $md5ValueLen / 2);return hex2bin($key);}}$cipher = 'DES-EDE-CBC';$msg = 'HelloWorld';$key = '12345678';$iv = "\x00\x00\x00\x00\x00\x00\x00\x00";$des = new DesEdeCbc($cipher, $key, $iv);// 加密$msg = $des->encrypt($msg);echo '加密后: ' . $msg . PHP_EOL;// 解密$src = $des->decrypt($msg);echo '解密后: ' . $src . PHP_EOL;
3. 一點(diǎn)說(shuō)明
可以根據(jù)實(shí)際情況調(diào)整加密方式、key的填充方式、及iv向量來(lái)滿足不同的需求。
更多相關(guān)PHP7文章請(qǐng)?jiān)L問(wèn):《PHP7》教程
總結(jié)
以上是生活随笔為你收集整理的php openssl des ecb,PHP7 OpenSSL DES-EDE-CBC加解密的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 妈妈的智商会影响孩子的智商吗?
- 下一篇: php编译优化,浅析使用Turck-mm