md5解密代码_PHP7 OpenSSL DESEDECBC加解密

852ea5ee6f197d28f77da2ae9cc1b33f.png

php中文网最新课程

每日17点准时技术干货分享

178c03daf451a43e89486b8d356dd776.png

0c530aeb57e078925ab58a642abd7508.gif

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向量来满足不同的需求。

-END-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值