Home  >  Article  >  Backend Development  >  How to replace mcrypt in php

How to replace mcrypt in php

藏色散人
藏色散人Original
2022-10-31 09:46:321924browse

How to replace mcrypt with php: 1. Open the corresponding php file; 2. Find the original encryption and decryption code; 3. Use the "openssl_encrypt" and "openssl_decrypt" methods to replace it.

How to replace mcrypt in php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.

php How to replace mcrypt?

Mcrypt encryption and decryption alternative in php7.4

Problem description

The mcrypt_encrypt and mcrypt_decrypt functions have been abandoned since PHP 7.1.0. The original project (php5. 6) The mcrypt_encrypt and mcrypt_decrypt functions used in php7.1 and later environments will prompt that the function cannot be found, and you need to use openssl_encrypt and openssl_decrypt instead.

Solution

********************Encryption*************** ********

<?php
/**
 * 原加密方法方法
 * @param $str
 * @param string $key
 * @return string
 */
function des_encrypt($str, $key=&#39;uK9pFn56&#39;) {
        $block = mcrypt_get_block_size(&#39;des&#39;, &#39;ecb&#39;);
        $pad = $block - (strlen($str) % $block);
        $str .= str_repeat(chr($pad), $pad);
        return base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB));
}
$str = "123123";
var_dump(des_encrypt($str));  //加密结果:BKG4i231OB0=
rrree

************************Decryption************ ************

<?php
/**
 * openssl_encrypt加密替代方法
 * @param $str
 * @param string $key
 * @return string
 */
function des_encrypt($str, $key = &#39;uK9pFn56&#39;)
{
    return base64_encode(openssl_encrypt($str, "DES-ECB", $key, OPENSSL_RAW_DATA, ""));
}
$str = "123123";
var_dump(des_encrypt($str));  //加密结果:BKG4i231OB0=
/**
 * 原解密方法
 * @param $str
 * @param string $key
 * @return string
 */
function des_decrypt($str, $key=&#39;uK9pFn56&#39;) {
        $str = mcrypt_decrypt(MCRYPT_DES, $key, base64_decode($str), MCRYPT_MODE_ECB);
        $len = strlen($str);
        $block = mcrypt_get_block_size(&#39;des&#39;, &#39;ecb&#39;);
        $pad = ord($str[$len - 1]);
        return substr($str, 0, $len - $pad);
}
var_dump(des_decrypt("BKG4i231OB0="));  //解密结果:123123

Recommended study: "PHP Video Tutorial"

The above is the detailed content of How to replace mcrypt in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn