How PHP uses MCrypt to implement cryptographic decryption instance code

Source: Internet
Author: User
Tags mcrypt
PHP comes with quite a bit of encryption, so let's take a look at how the mcrypt extension works. is also in the work need to use this thing encrypted access to the user's cookie value, seriously learn the content of this aspect.

1. Introduction

MCrypt is an extension of PHP that completes the encapsulation of commonly used cryptographic algorithms. In fact, the extension is the MCrypt Standard Class library encapsulation, MCrypt completed a considerable number of commonly used cryptographic algorithms, such as DES, TripleDES, Blowfish (default), 3-way, safer-sk64, safer-sk128, Twofish , TEA, RC2 and GOST encryption algorithms, and provides a model of CBC, OFB, CFB, and ECB four block encryption.

2. Installation and use

To use this extension, you must first install the MCrypt Standard class library. This extension is compiled and installed in the same way as regular PHP extensions, not in detail.

3. Four types of block encryption models

MCrypt supports four types of block encryption models, briefly described below:

①. MCRYPT_MODE_ECB (Electronic codebook) is suitable for encrypting small amounts of random data, such as encrypting a user's login password.

②. MCRYPT_MODE_CBC (cipher block chaining) is suitable for encrypting important file types with higher security levels.

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

④. MCRYPT_MODE_OFB (output feedback, in 8bit) is compatible with the CFB mode, but is more secure than the CFB mode. The CFB mode causes an encrypted error spread, and if a byte fails, all subsequent byte of it will be faulted. The OFB mode does not have this problem. However, the security of this mode is not very high, it is not recommended.

⑤. MCRYPT_MODE_NOFB (output feedback, in nbit) is compatible with OFB, and is more secure due to the use of block operation algorithms.

⑥. Mcrypt_mode_stream is an additional model provided for wake or RC4 stream encryption algorithms.

NOFB and stream are only valid if the version number of Mycrypt is greater than or equal to libmcrypt-2.4.x. (This is basically more than this version, the latest major version of Libmcrypt is now 4)

4. View supported algorithms and models

①. Mcrypt_list_modes () lists the models that are currently supported by the environment

②. MCRYPT_LIST_ALGORITHMS () lists the algorithms currently supported by the environment

such as command line execution:

The code is as follows:

Php-r "Var_dump (Mcrypt_list_modes ()); Var_dump (Mcrypt_list_algorithms ()); "

You can list all the 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 ' clock @ the Secret place."; $encrypted _data = MCRYPT_ECB (Mcrypt_3des, $key, $input, mcrypt_encrypt);? >

The simplest way, as shown in Example 1, is to encrypt the $input using the 3DES algorithm, and the encryption key is $key. However, this method of direct invocation has not been used by the official recommendation, and it is recommended that you do not use this method in development, not necessarily the day that the methods can not be used. When invoked using this method under PHP5, you can see a Warning message that indicates "PHP Warning:attempt to uses an empty IV, which was not recommend".

The official recommended way to use 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 ' clock in the secret Place.";    Opens a mcrypt, or MCrypt-type resource object that uses the ECB mode and uses 3DES as the encryption algorithm.    $td = Mcrypt_module_open (' TripleDES ', ' ', ' ECB ', ');    Create IV (Initialization vector)    $iv = Mcrypt_create_iv (Mcrypt_enc_get_iv_size ($TD), mcrypt_rand);    Mcrypt_generic_init ($TD, $key, $iv)    based on the key and IV initialization $TD, complete the initialization of memory allocation, etc. Encrypt    $encrypted _data = Mcrypt_generic ($TD, $input);    Initialize $TD, release resource    mcrypt_generic_deinit ($TD);    Close the resource object, Exit     mcrypt_module_close ($TD); >


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

The decryption process is basically the same as encryption, as long as the Mcrypt_generic ($TD, $input) is replaced with Mdecrypt_generic ($TD, $input), and the rest are identical. Of course, for a symmetric cryptographic algorithm such as 3DES, the key used for encryption and decryption must be exactly the same.

6. About IV

Not all models require IV. CFB and OFB are required to have IV, CBC and EBC are optional. For the mode of required IV, the value of the IV for encryption and decryption must be exactly the same, and CBC and EBC do not have this requirement. can be the same or different, no matter.

7. A simple function of the cryptographic decryption class

The code is as follows:

Class Ampcrypt {private static function GetKey () {return MD5 (' Examplekey ');         public static function Encrypt ($value) {$td = Mcrypt_module_open (' TripleDES ', ' ', ' ECB ', ');         $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 (' TripleDES ', ' ', ' ECB ', ');         $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; }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.