首頁  >  文章  >  後端開發  >  PHP7 OpenSSL DES-EDE-CBC加解密

PHP7 OpenSSL DES-EDE-CBC加解密

藏色散人
藏色散人轉載
2020-01-08 17:41:233219瀏覽

1. 條件限制

之前PHP5上常使用的mcrypt函式庫在PHP7.1 上已經移除,故我們採用openssl對資料進行加解密。

加密方式採用DES-EDE-CBC方式。

金鑰填入方式為:採用24位元金鑰,先將key進行MD5校驗取值,得出16位元字串,再取key MD5校驗值前8位元追加到先前的取值後面。由此組裝出24位元的密鑰。

2. 程式碼分享

<?php
class 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位长度的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 = &#39;DES-EDE-CBC&#39;;
$msg = &#39;HelloWorld&#39;;
$key = &#39;12345678&#39;;
$iv  = "\x00\x00\x00\x00\x00\x00\x00\x00";
$des = new DesEdeCbc($cipher, $key, $iv);
// 加密
$msg = $des->encrypt($msg);
echo &#39;加密后: &#39; . $msg . PHP_EOL;
// 解密
$src = $des->decrypt($msg);
echo &#39;解密后: &#39; . $src . PHP_EOL;

3. 一點說明

可以根據實際情況調整加密方式、key的填充方式、及iv向量來滿足不同的需求。

更多相關PHP7文章請上:《PHP7》教學

以上是PHP7 OpenSSL DES-EDE-CBC加解密的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除