What is the PHP mcrypt encryption extension? Specific introduction to the MCrypt extension

Source: Internet
Author: User
Tags decrypt mcrypt
In specific project development, sometimes we may need to encrypt some data in front-end interactions. SoPHP provides mcrypt encryption extension to encrypt and decrypt data. Next, let's take a look at the introduction of the MCrypt extension.

One,the installation of MCrypt expansion

  in the lower version of PHP needs to explicitly add a reference to the extension in the configuration file php.ini, and to ensure that the extension reference directory has the appropriate extension file, in the later version of PHP, Windows appears to default to open the MCrypt extension, do not need to configure in the configuration file php.ini, in the extension reference directory also does not see the phase Extension files, the corresponding mcrypt.so extensions will need to be installed under Linux.

The MCrypt extension supports a variety of cryptographic algorithms and patterns that can be used to display supported cryptographic algorithms and encryption modes using MCRYPT_LIST_ALGORITHMS () and Mcrypt_list_modes ().

Second, Use of the mcrypt extension

Encryption

1. turn on encryption algorithms and patterns

Mcrypt_module_open (' TripleDES ', ' ', ECB ', ');

The first parameter is the name of the encryption algorithm used, corresponding to the MCRYPT_LIST_ALGORITHMS () output of the encryption algorithm, the third parameter corresponds to the encrypted mode, corresponding to the mcrypt_list_modes () output of the support encryption mode.

2. Creating an initialization vector

Mcrypt_create_iv (Mcrypt_enc_get_iv_size ($TD), Mcrypt_rand);

PS. Under the window platform, the second parameter is fixed using the Mcrypt_rand

3. initializing an encryption buffer

Mcrypt_generic_init ($TD, $key, $IV);

$TD is the returned cryptographic descriptor, $key as the encryption key, $IV as the initialization vector

4. Data Encryption

$encrypted _data = Mcrypt_generic ($TD, $data);

$TD is the cryptographic descriptor, $data the data before encryption, and the data encryption function returns the encrypted string.

5. end encryption, perform cleanup work

Mcrypt_generic_deinit ($TD);

Decrypt

1. Open decryption algorithm and pattern, ditto, get $TD Decrypt descriptor

2. Create initialization vectors, ditto, get $iv initialization vectors

3. initial dissolve secret buffer

Mcrypt_generic_init ($TD, $key, $IV);

4. Data decryption

$decrypted _data = Mdecrypt_generic ($TD, $encrypted _data);

PS. $encrypted _data is the ciphertext before decryption, $decrypted _data as the decrypted plaintext.

Demo Demo:

<?php/* Open encryption algorithm and Mode */$TD = Mcrypt_module_open (' rijndael-256 ', ' ', ' ofb ', '    ');      /* Create an initial vector and detect the key length. * Windows platform please use Mcrypt_rand.    */$iv = Mcrypt_create_iv (Mcrypt_enc_get_iv_size ($TD), mcrypt_dev_random);    $ks = Mcrypt_enc_get_key_size ($TD);    /* Create key */$key = substr (MD5 (' very secret key '), 0, $ks);    /* Initialize encryption */Mcrypt_generic_init ($TD, $key, $IV);    /* Encrypt data */$encrypted = Mcrypt_generic ($TD, ' This is very important data ');    /* End encryption, perform cleanup work */Mcrypt_generic_deinit ($TD);    /* Initial dissolve Secret module */Mcrypt_generic_init ($TD, $key, $IV);    /* Decrypt data */$decrypted = Mdecrypt_generic ($TD, $encrypted);    /* End decryption, perform cleanup, and close module */Mcrypt_generic_deinit ($TD);    Mcrypt_module_close ($TD); /* Display text */echo trim ($decrypted). "\ n";? 

Third, Implementing an AES encryption class

<?php/** * PHP AES Encryption decryption class * Created by Phpstorm. * User:ahao * DATE:2016/11/3 * time:0:03 */class pubencrypt{public static $key = ' 123454536f667445454d537973576562 '  ; Default Key/** * AES Encryption * @param $data plaintext * @param null $KEY encryption Key * @return Array|string */Publ        IC static function Aesencrypt ($data, $key = null) {$data = Trim ($data);        if ($data = = ") return";            try{if (!extension_loaded (' MCrypt ')) throw new Exception (' Current PHP environment does not load mcrypt extensions ');            Open cryptographic algorithms and patterns $module = Mcrypt_module_open (mcrypt_rijndael_128, ', MCRYPT_MODE_CBC, ');            $key = self::substr ($key = = null? Self:: $key: $key, 0, Mcrypt_enc_get_key_size ($module));            $IV = substr (MD5 ($key), 0, Mcrypt_enc_get_iv_size ($module));            Initialize cryptographic mcrypt_generic_init ($module, $key, $IV);            Encrypted Data $encrypt = Mcrypt_generic ($module, $data); Anti-initialize release resource Mcrypt_geneRic_deinit ($module);            Close Resource object Exit Mcrypt_module_close ($module);        Return array (' status ' = = True, ' data ' = Base64_encode ($encrypt));            }catch (Exception $e) {$error = $e->getmessage ();            $data = Array (' status ' = = False, ' msg ' = = $error);        return $data; }}/** * AES decryption * @param $encrypted redaction * @param null $key decryption key * @return array|string * * PU        Blic static function Aesdecrypt ($encrypted, $key = null) {$encrypted = Trim ($encrypted);        if ($encrypted = = ") return";            try{if (!extension_loaded (' MCrypt ')) throw new Exception (' Current PHP environment does not load mcrypt extensions ');            $encrypted = Base64_decode ($encrypted);            $module = Mcrypt_module_open (mcrypt_rijndael_128, ', MCRYPT_MODE_CBC, ');     $key = self::substr ($key = = null? Self:: $key: $key, 0, Mcrypt_enc_get_key_size ($module));       $IV = substr (MD5 ($key), 0, Mcrypt_enc_get_iv_size ($module));            Mcrypt_generic_init ($module, $key, $IV);            $decrypted = Mdecrypt_generic ($module, $encrypted);            Mcrypt_generic_deinit ($module);            Mcrypt_module_close ($module);        Return array (' status ' = = True, ' data ' = = RTrim ($decrypted, "\ n"));            }catch (Exception $e) {$error = $e->getmessage ();            $data = Array (' status ' = = False, ' msg ' = = $error);        return $data; }}/** * Intercept String * @param $string the truncated string * @param $start start position * @param $length intercept length * @retur n String intercept */private static function substr ($string, $start, $length) {return extension_loaded (' Mbstring ')?    Mb_substr ($string, $start, $length, ' 8bit '): substr ($string, $start, $length); }}

PS. Benefits of using Data encryption: The data is transmitted between the front and back of a string, which prevents data from being caught by crawlers, avoids the leakage of sensitive data, and effectively prevents the guessing of data items from malicious requests to data manipulation interfaces.

Second, Use of the mcrypt extension

Encryption

1. turn on encryption algorithms and patterns

Mcrypt_module_open (' TripleDES ', ' ', ECB ', ');

The first parameter is the name of the encryption algorithm used, corresponding to the MCRYPT_LIST_ALGORITHMS () output of the encryption algorithm, the third parameter corresponds to the encrypted mode, corresponding to the mcrypt_list_modes () output of the support encryption mode.

2. Creating an initialization vector

Mcrypt_create_iv (Mcrypt_enc_get_iv_size ($TD), Mcrypt_rand);

PS. Under the window platform, the second parameter is fixed using the Mcrypt_rand

3. initializing an encryption buffer

Mcrypt_generic_init ($TD, $key, $IV);

$TD is the returned cryptographic descriptor, $key as the encryption key, $IV as the initialization vector

4. Data Encryption

$encrypted _data = Mcrypt_generic ($TD, $data);

$TD is the cryptographic descriptor, $data the data before encryption, and the data encryption function returns the encrypted string.

5. end encryption, perform cleanup work

Mcrypt_generic_deinit ($TD);

Decrypt

1. Open decryption algorithm and pattern, ditto, get $TD Decrypt descriptor

2. Create initialization vectors, ditto, get $iv initialization vectors

3. initial dissolve secret buffer

Mcrypt_generic_init ($TD, $key, $IV);

4. Data decryption

$decrypted _data = Mdecrypt_generic ($TD, $encrypted _data);

PS. $encrypted _data is the ciphertext before decryption, $decrypted _data as the decrypted plaintext.

Related recommendations:

Summary of usage of PHP encryption extension MCrypt

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.