Encryption and decryption example code of php mcrypt

怪我咯
Release: 2023-03-13 18:16:01
Original
1240 people have browsed it

1. Introduction

Mcrypt is an extension of PHP that completes the encapsulation of commonly used encryption algorithms. In fact, this extension is an encapsulation of the mcrypt standard class library. mcrypt has completed quite a few commonly used encryption algorithms, such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST encryption algorithm and provides four block encryption models: CBC, OFB, CFB and ECB.

2. Installation and use

To use this extension, you must first install the mcrypt standard class library, which can be downloaded from http://mcrypt.sourceforge.net. The compilation and installation methods of this extension are the same as those of regular PHP extensions, so they will not be explained in detail.

3. Four block encryption models

Mcrypt supports four block encryption models, a brief description is as follows:

①. MCRYPT_MODE_ECB (electronic codebook) Suitable for encrypting small amounts of random data, such as encrypting user login passwords.

②. MCRYPT_MODE_CBC (cipher block chaining) is suitable for important file types with high encryption security level.

③. MCRYPT_MODE_CFB (cipher feedback) is suitable for situations where every byte of the data stream needs to be encrypted.

④. MCRYPT_MODE_OFB (output feedback, in 8bit) is compatible with CFB mode, but more secure than CFB mode. CFB mode will cause encryption errors to spread. If one byte is wrong, all subsequent bytes will be wrong. OFB mode does not have this problem. However, this mode is not very safe and is not recommended.

⑤. MCRYPT_MODE_NOFB (output feedback, in nbit) is compatible with OFB and has higher security due to the use of block operation algorithm.

⑥. MCRYPT_MODE_STREAM is an additional model provided for stream encryption algorithms such as WAKE or RC4.

NOFB and STREAM are only valid when the version number of mycrypt is greater than or equal to libmcrypt-2.4.x. (Now they are basically larger than this version, and the latest major version of libmcrypt has reached 4)

4. Check the supported algorithms and models

①. mcrypt_list_modes () List the models supported by the current environment

②. mcrypt_list_algorithms() List the algorithms supported by the current environment

If executed from the command line:

The code is as follows:

php -r "var_dump(mcrypt_list_modes()); var_dump(mcrypt_list_algorithms());"
Copy after login

to list all results.

5. How to use

Example 1:

<?php
$key = "this is a secret key";
$input = "Let us meet at 9 o&#39;clock at the secret place.";
$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>
Copy after login

The simplest way is as shown in Example 1, which shows the use of $input The 3DES algorithm is used for encryption, and the encryption key is $key. However, the method of direct calling is no longer officially recommended, and it is also recommended that you do not use this method in development. This method may not be available one day. When calling this method under php5, you can see a warning message, prompting "PHP Warning: attempt to use an empty IV, which is NOT recommend".

The officially recommended usage is shown in Example 2

Example 2:

<?php
    $key = "this is a secret key";
    $input = "Let us meet at 9 o&#39;clock at the secret place.";
    // 打开mcrypt,或者mcrypt类型的资源对象,该对象使用ecb模式,使用3des作为加密算法。
    $td = mcrypt_module_open(&#39;tripledes&#39;, &#39;&#39;, &#39;ecb&#39;, &#39;&#39;);
    // 创建iv(初始化向量)
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    // 根据密钥和iv初始化$td,完成内存分配等初始化工作
    mcrypt_generic_init($td, $key, $iv);
    // 进行加密
    $encrypted_data = mcrypt_generic($td, $input);
    // 反初始化$td,释放资源
    mcrypt_generic_deinit($td);
    // 关闭资源对象,退出
     mcrypt_module_close($td);
?>
Copy after login

The above process completes the data encryption process. First select the encryption algorithm and encryption mode to create the resource object and IV of mcrypt, then initialize the buffer (memory) required for encryption, release the buffer after encryption, and finally close the resource object.

The decryption process is basically the same as encryption. Just replace mcrypt_generic($td, $input) with mdecrypt_generic($td, $input). The other parts are exactly the same. Of course, for a symmetric encryption algorithm like 3des, the keys used for encryption and decryption must be exactly the same.

6. About IV

Not all models require IV. CFB and OFB must have IV, while CBC and EBC are optional. For the required IV mode, the values ​​of the encrypted and decrypted IV must be exactly the same. CBC and EBC do not have this requirement. It can be the same or different, it doesn't matter.

7. A simple encryption and decryption class

class AMPCrypt {
    private static function getKey(){
        return md5(&#39;exampleKey&#39;);
     }
    public static function encrypt($value){
         $td = mcrypt_module_open(&#39;tripledes&#39;, &#39;&#39;, &#39;ecb&#39;, &#39;&#39;);
         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
         $key = substr(self::getKey(), 0, mcrypt_enc_get_key_size($td));
         mcrypt_generic_init($td, $key, $iv);
         $ret = base64_encode(mcrypt_generic($td, $value));
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
        return $ret;
     }
    public static function dencrypt($value){
         $td = mcrypt_module_open(&#39;tripledes&#39;, &#39;&#39;, &#39;ecb&#39;, &#39;&#39;);
         $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
         $key = substr(self::getKey(), 0, mcrypt_enc_get_key_size($td));
         $key = substr(self::getKey(), 0, mcrypt_enc_get_key_size($td));
         mcrypt_generic_init($td, $key, $iv);
         $ret = trim(mdecrypt_generic($td, base64_decode($value))) ;
         mcrypt_generic_deinit($td);
         mcrypt_module_close($td);
        return $ret;
     }
}
Copy after login

The above is the detailed content of Encryption and decryption example code of php mcrypt. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!