Home  >  Article  >  Backend Development  >  How to use 'DES-EDE-CBC' encryption and decryption in PHP7

How to use 'DES-EDE-CBC' encryption and decryption in PHP7

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-05-12 09:26:412310browse

This article will introduce to you the encryption and decryption method using "DES-EDE-CBC" in PHP7. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to use 'DES-EDE-CBC' encryption and decryption in PHP7

1. Conditional constraints

The mcrypt library commonly used on PHP5 has been removed on PHP7.1, so we use openssl to process the data Encryption and decryption.

The encryption method adopts DES-EDE-CBC method.

The key filling method is: using a 24-bit key, first perform MD5 verification on the key to obtain a 16-bit string, and then take the first 8 digits of the key MD5 verification value and append them to the previous value. value behind. A 24-bit key is assembled from this.

2. Code sharing

<?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 = &#39;DES-EDE-CBC&#39;;
$msg = &#39;HelloWorld&#39;;
$key = &#39;12345678&#39;;
$iv  = "\x00\x00\x00\x00\x00\x00\x00\x00";

$des = new DesEdeCbc($cipher, $key, $iv);

// 加密
$msg = $des->encrypt($msg);
echo &#39;加密后: &#39; . $msg . PHP_EOL;

// 解密
$src = $des->decrypt($msg);
echo &#39;解密后: &#39; . $src . PHP_EOL;

3. A little explanation

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

Recommended learning: php video tutorial

The above is the detailed content of How to use 'DES-EDE-CBC' encryption and decryption in PHP7. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete