Php mcrypt-based encryption and decryption instance

Source: Internet
Author: User
Tags mcrypt
This article mainly introduces the implementation of mcrypt-based encryption and decryption in php, and analyzes the principles and specific implementation methods of mcrypt encryption and decryption in the form of examples, which is of great practical value, for more information, see

This article mainly introduces the implementation of mcrypt-based encryption and decryption in php, and analyzes the principles and specific implementation methods of mcrypt encryption and decryption in the form of examples, which is of great practical value, for more information, see

This example describes how to implement encryption and decryption Based on mcrypt in php. Share it with you for your reference. The specific implementation method is as follows:

PHP comes with a lot of encryption methods. Here we will look at the use of mcrypt extensions. It is also necessary to encrypt the user's Cookie value at work. I carefully studied this aspect.

1. Introduction

Mcrypt is an extension of PHP and encapsulates common encryption algorithms. In fact, the extension is the encapsulation of mcrypt standard class library, mcrypt completed a lot of common encryption algorithms, such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST encryption algorithms, 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. The compilation and installation method of this extension is the same as that of the conventional php extension, which is not described in detail.

3. Four block encryption Models

Mcrypt supports four block encryption models, which are described as follows:

①. MCRYPT_MODE_ECB (electronic codebook) is suitable for encrypting a small amount of random data, such as encrypting users' logon passwords.

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

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

④. MCRYPT_MODE_OFB (output feedback, in 8bit) is compatible with CFB mode, but is safer than CFB mode. The CFB mode will cause the spread of encryption errors. If a byte fails, all subsequent bytes will go wrong. OFB mode does not have this problem. However, this mode is not highly secure and is not recommended.

⑤. MCRYPT_MODE_NOFB (output feedback, in nbit) is compatible with OFB. Because of the block operation algorithm, the security is higher.

6. MCRYPT_MODE_STREAM is an extra model provided for stream encryption algorithms such as WAKE and RC4.

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

4. view supported algorithms and Models

①. Mcrypt_list_modes () lists models supported by the current environment

②. Mcrypt_list_algorithms () lists the algorithms supported by the current environment

For example, execute the following command line:

The Code is as follows:

Php-r "var_dump (mcrypt_list_modes (); var_dump (mcrypt_list_algorithms ());"


All results are listed.

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 at the secret place .";
$ Encrypted_data = mcrypt_ecb (MCRYPT_3DES, $ key, $ input, MCRYPT_ENCRYPT );
?>

The simplest method is shown in Example 1. This method indicates that $ input is encrypted using the 3DES algorithm, and the encryption key is $ key. however, the method directly called in this method is no longer officially recommended. We also recommend that you do not use this method during development. This method may not be available any day. When using this method in php5, you can see a warning message, prompting "PHP Warning: attempt to use an empty IV, which is NOT recommend ".

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 'clock at the secret place .";
// Open mcrypt or mcrypt resource object. This object uses ecb mode and 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 );
// Initialize $ td based on the key and iv to complete initialization such as memory allocation
Mcrypt_generic_init ($ td, $ key, $ iv );
// Encrypt
$ Encrypted_data = mcrypt_generic ($ td, $ input );
// Uninitialize $ td to release resources
Mcrypt_generic_deinit ($ td );
// Close the resource object and exit
Mcrypt_module_close ($ td );
?>


The above process completes the data encryption process. 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 it, then release the buffer, and finally close the resource object.

The decryption process is basically the same as the encryption process. You only need to replace mcrypt_generic ($ td, $ input) with mdecrypt_generic ($ td, $ input), and the rest is the same. Of course, for symmetric encryption algorithms such as 3des, keys used for encryption and decryption must be identical.

6. About IV

Not all models require IV. Neither CFB nor OFB must have IV, while CBC and EBC are optional. For the mandatory IV mode, the values of the IV values for encryption and decryption must be the same, and the CBC and EBC do not have this requirement. It can be the same or different. It doesn't matter.

7. A simple function of encryption and 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;
}
}

I hope this article will help you with PHP programming.

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.