RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
PHP7实现OpenSSLDES-EDE-CBC加密和解密

1. 条件约束

目前创新互联公司已为上千的企业提供了网站建设、域名、网络空间、网站改版维护、企业网站设计、赤坎网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

之前PHP5上常使用的mcrypt库在PHP7.1+上已经被移除,故我们采用openssl对数据进行加解密。

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

密钥填充方式为:采用24位密钥,先将key进行MD5校验取值,得出16位字串,再取key MD5校验值前8位追加到先前的取值后面。由此组装出24位的密钥。

2. 代码分享

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 OpenSSL DES-EDE-CBC加解密的详细内容,更多请关注创新互联其它相关文章!


网页名称:PHP7实现OpenSSLDES-EDE-CBC加密和解密
本文链接:http://sczitong.cn/article/pieocj.html