PHP based MCrypt encryption and decryption instance _php skills

Source: Internet
Author: User
Tags mcrypt md5 sha1 encryption

This article illustrates the method of PHP based on MCrypt to implement encryption and decryption. Share to everyone for your reference. The implementation methods are as follows:

PHP has a very large number of encryption methods, here we look at the use of mcrypt extension. Also in the work need to use this thing to encrypt access to the user's cookie value, seriously learn this aspect of the content.

1. Introduction

MCrypt is an extension of PHP that completes the encapsulation of commonly used cryptographic algorithms. In fact, the extension is for 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 provide a four-block encryption model for CBC, OFB, CFB and ECB.

2. Installation and use

To use this extension, you must first install the MCrypt Standard class library, which you can download in http://mcrypt.sourceforge.net. The extensions are compiled and installed in the same way as regular PHP extensions and are not described in detail.

3. Four kinds of block encryption model

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 important file types with high encryption security levels.

③. 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 the CFB model, but is more secure than the CFB model. The CFB pattern causes an error in the encryption to spread, and if a byte error occurs, all subsequent byte will be faulted. OFB mode does not have this problem. However, the security of the pattern is not very high and is not recommended.

⑤. MCRYPT_MODE_NOFB (output feedback, in nbit) and OFB compatibility, because of the use of block operation algorithm, security is higher.

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

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

4. View supported algorithms and models

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

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

such as command line execution:

Copy Code code 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:

Copy Code code as follows:
<?php
$key = "This is a secret key";
$input = "Let us meet in 9 o ' clock at the secret Place.";
$encrypted _data = MCRYPT_ECB (Mcrypt_3des, $key, $input, Mcrypt_encrypt);
?>

The simplest way, as shown in Example 1, this method shows that the encryption key is $key when the $input is encrypted using a 3DES algorithm. However, this method of direct invocation has not been officially recommended, and it is recommended that you do not use this approach in development, not necessarily one day the method can not be used. When invoked this way under PHP5, you can see a Warning message that prompts "PHP warning:attempt to use a empty IV, which is not recommend".

Official recommendations are used as shown in Example 2

Example 2:

Copy Code code as follows:
<?php
$key = "This is a secret key";
$input = "Let us meet in 9 o ' clock at the secret Place.";
Open the MCrypt, or MCrypt type of resource object that uses 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);
Completes initialization of memory allocation, based on key and IV initialization $TD
Mcrypt_generic_init ($TD, $key, $IV);
For encryption
$encrypted _data = Mcrypt_generic ($TD, $input);
Reverse initialize $TD, releasing resources
Mcrypt_generic_deinit ($TD);
Close Resource object, exit
Mcrypt_module_close ($TD);
?>

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

Decryption process and encryption are basically the same, as long as the Mcrypt_generic ($TD, $input) replaced by Mdecrypt_generic ($TD, $input) on it, the other parts are identical. Of course, for the 3DES symmetric encryption algorithm, encryption, decryption of the key used must be exactly the same.

6. About IV

Not all models require IV. The CFB and OFB are required to have IV, CBC and EBC are optional. For the mode of the required IV, the value of the IV that is encrypted and decrypted must be exactly the same, and CBC and EBC have no such requirement. can be the same or can be different, it doesn't matter.

7. A simple function of the encryption and decryption class

Copy Code code 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;
}
}

PS: About encryption technology, the site also provides the following encryption tools for your reference to use:

MD5 Online encryption tool:Http://tools.jb51.net/password/CreateMD5Password

Escape Encryption/Decryption tool:http://tools.jb51.net/password/escapepwd

Online SHA1 encryption tool:Http://tools.jb51.net/password/sha1encode

short link (short URL) online generation tool:http://tools.jb51.net/password/dwzcreate

short link (short URL) online restore tool:Http://tools.jb51.net/password/unshorturl

High Strength Password generator:Http://tools.jb51.net/password/CreateStrongPassword

I hope this article will help you with your PHP program design.

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.