zoukankan      html  css  js  c++  java
  • PHP加密扩展库-openssl

    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 = "x00x00x00x00x00x00x00x00";
    $des = new DesEdgCbc($cipher, $key, $iv);
    //加密
    $msg = $des->encrypt($msg);
    echo '加密后:'.$msg.'<br/>';
    //解密
    $src = $des->decrypt($msg);
    echo '解密后:'.$src.'<br/>';

    结果为:

    3. 一点说明

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

     

  • 相关阅读:
    Javascript MVC学习杂记3
    Backbone.js 0.9.2 源码分析收藏
    Javascript MVC学习杂记2
    Javascript MVC学习杂记1
    C语言string.h中常用字符函数介绍
    10点网页设计要注意的细节
    js日期函数
    结合回调函数介绍下泛型函数
    【转载】互斥量和信号量的区别
    设计模式之Singleton
  • 原文地址:https://www.cnblogs.com/chenyingying0/p/12910951.html
Copyright © 2011-2022 走看看