Home  >  Article  >  Backend Development  >  Detailed explanation of how PHP uses mcrypt to implement encryption and decryption example code

Detailed explanation of how PHP uses mcrypt to implement encryption and decryption example code

伊谢尔伦
伊谢尔伦Original
2017-07-08 10:39:241484browse

PHP comes with quite a few encryption methods. Here we take a look at how to use the mcrypt extension. I also need to use this thing to encrypt the value of the user's cookie at work, and I have studied this aspect seriously.

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. 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 each 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. 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());"

to list all results.

5. How to use

Example 1:

The code is as follows:

<?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);
?>

The simplest way is as in Example 1 Indicates that this method uses the 3DES algorithm to encrypt $input, 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. It is not necessarily One day this method will no longer work. 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:

The code is as follows:

<?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);
?>


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

The code is as follows:

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;
     }
}

The above is the detailed content of Detailed explanation of how PHP uses mcrypt to implement encryption and decryption example code. 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