VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 网站开发 > PHP >
  • php教程之PHP加密扩展库-openssl

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

PHP加密扩展库—Mcrypt扩展库

概要:

php从7.0升级到7.1废弃了一个扩展,即mcrypt扩展,虽然安装上扩展也能正常使用,但是会发出警告,告诉我们mcrypt相关方法已经被废弃,到了7.2,已经被移除,因此不建议继续使用。

 

来源:

在使用微信,淘宝第三方开发文档的时候,很多地方还是沿用以前的加密方法,这个时候我们需要找到替换的方法,openssl就是不错的选择,这就需要我们清楚mcrypt和openssl之间的差异,以便保证数据加解密的一致性。

详解mcrypt和openssl来实现AES-128/192/256-CBC加解密

 

1. 条件约束

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

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

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

 

2. 代码分享

复制代码
<?php

class DesEdgCbc {
    private $cipher, $key, $iv;

    public function __construct($cipher, $key, $iv){
        $this->cipher = $cipher;
        $this->key = $this->getFormatKey($key);
        $this->iv = $iv;
    }

    /**
     * [加密]
     * @param  [type] $msg [description]
     * @return [string]      [description]
     */
    public function encrypt($msg){
        $des = @openssl_encrypt($msg, $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);
        return base64_encode($des);
    }

    /**
     * 解密
     * @param  [type] $msg [description]
     * @return [string]      [description]
     */
    public function decrypt($msg){
        return @openssl_decrypt(base64_decode($msg), $this->cipher, $this->key, OPENSSL_RAW_DATA, $this->iv);
    }

    public function getFormatKey($skey){
        $md5Value = md5($skey);
        $md5ValueLen = strlen($md5Value);
        $key = $md5Value.substr($md5ValueLen, 0, $md5ValueLen/2);
        return hex2bin($key);//把十六进制值转换为 ASCII 字符
    }
}

$cipher = 'DES-EDE-CBC';
$msg = 'hello, cyy';
$key = '123456789';
$iv = "\x00\x00\x00\x00\x00\x00\x00\x00";
$des = new DesEdgCbc($cipher, $key, $iv);
//加密
$msg = $des->encrypt($msg);
echo '加密后:'.$msg.'<br/>';
//解密
$src = $des->decrypt($msg);
echo '解密后:'.$src.'<br/>';
复制代码

 

结果为:

 

 

3. 一点说明

可以根据实际情况调整加密方式、key的填充方式、及iv向量来满足不同的需求。

相关教程