技术圈开发者交流群:

PHP7版的Des加解密,支持ECB,CBC等模式,兼容java、C#

最近对接一大堆接口,找了各种des加解密,很多都是php7以下的,要知道mcrypt_decrypt此类的方法再php7以上已经过时或废除了

Warning
This function has been DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0. Relying on this function is highly discouraged.

搞了好久,好不容易看到了这个 https://blog.csdn.net/qq43599939/article/details/80226482 ,终于将C#、Java的代码转换成了php7的代码:

<?php

/**
 * Des加解密,兼容java、C#
 */
class Des
{

    /**
     * 加密
     * @author TechLee
     * @param  string $input
     * @param  string $key
     * @param  string $method
     * @param  string $iv
     * @return string
     */
    public static function encrypt($input, $key, $method = 'DES-ECB', $iv = null)
    {
        $iv = $iv ? $iv : self::createIv();
        return base64_encode(openssl_encrypt($input, $method, $key, OPENSSL_RAW_DATA, $method == 'DES-ECB' ? '' : $iv));
    }

    /**
     * 解密
     * @author TechLee
     * @param  string $input
     * @param  string $key
     * @param  string $method
     * @param  string $iv
     * @return string
     */
    public static function decrypt($input, $key, $method = 'DES-ECB', $iv = null)
    {
        $iv = $iv ? $iv : self::createIv();
        return openssl_decrypt(base64_decode($input), $method, $key, OPENSSL_RAW_DATA, $method == 'DES-ECB' ? '' : $iv);
    }

    /**
     * 这个玩意相当于java里的
     * byte[] iv = { 0, 0, 0, 0, 0,0, 0, 0 }
     * 也相当于C#里的
     * IV = new byte[8];
     * @author TechLee
     * @return [type] [description]
     */
    public static function createIv()
    {
        return self::hexToStr("0000000000000000");
    }

    public static function hexToStr($hex)
    {
        $string = '';
        for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        }
        return $string;
    }
}
PHP 2018年08月24日 25651
鄂ICP备19028750号-1 @copyright 2024 tech1024.com