PHP7 OpenSSL DES-EDE-CBC加解密-PHP7

资源魔 42 0
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 = '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. 一点阐明

能够依据实际状况调整加密形式、key的填充形式、及iv向量来餍足没有同的需要。

更多相干PHP7文章请拜访:《PHP7》教程

以上就是PHP7 OpenSSL DES-EDE-CBC加解密的具体内容,更多请存眷资源魔其它相干文章!

标签: PHP7 php7开发教程 php7开发资料 php7开发自学

抱歉,评论功能暂时关闭!