PHP encryption extension library openssl

Keywords: PHP OpenSSL ascii

PHP encryption extension library Mcrypt extension library

Summary:

php upgrade from 7.0 to 7.1 discards an extension, that is, the mcrypt extension. Although the extension can be used normally on the installation, a warning will be given to tell us that the mcrypt related methods have been discarded and have been removed by 7.2. Therefore, it is not recommended to continue to use.

 

Source:

When using wechat and Taobao third party to develop documents, many places still use the previous encryption methods. At this time, we need to find a replacement method. openssl is a good choice, which requires us to know the difference between mcrypt and openssl, so as to ensure the consistency of data encryption and decryption.

Detailed explanation of mcrypt and openssl to realize AES-128/192/256-CBC encryption and decryption

 

1. Constraints

Previously, the mcrypt library which is often used in PHP5 has been removed from PHP7.1 +, so we use openssl to encrypt and decrypt the data.

The encryption mode is DES-EDE-CBC.

The key filling method is as follows: 24 bit key is used. First, MD5 verification value of key is obtained, and then the first 8 bits of MD5 verification value of key are added after the previous value. A 24 bit key is thus assembled.

 

2. Code sharing

<?php

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

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

    /**
     * [Encryption]
     * @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);
    }

    /**
     * decrypt
     * @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);//Convert hex value to ASCII character
    }
}

$cipher = 'DES-EDE-CBC';
$msg = 'hello, cyy';
$key = '123456789';
$iv = "\x00\x00\x00\x00\x00\x00\x00\x00";
$des = new DesEdgCbc($cipher, $key, $iv);
//encryption
$msg = $des->encrypt($msg);
echo 'After encryption:'.$msg.'<br/>';
//decrypt
$src = $des->decrypt($msg);
echo 'After decryption:'.$src.'<br/>';

 

The results are as follows:

 

 

3. One point

The encryption method, key filling method and iv vector can be adjusted according to the actual situation to meet different needs.

Posted by sloshire1 on Mon, 18 May 2020 08:15:14 -0700