Encrypt and decrypt using PHP MCrypt

Source: Internet
Author: User
Tags decrypt mcrypt asymmetric encryption

Digital Signature: Hash The data and the private key to get a message digest, along with the message itself, to the Client. The data signature emphasizes that the data received by the client is from a specific server, and the server has non-repudiation of the Data. The client determines whether the received message is from a specific server by confirming the correctness of the Signature.


Data encryption: Encrypt the data, there are two kinds of symmetric and asymmetric Encryption. Data is often decrypted using mcrypt and OpenSSL extensions in php. MCrypt is commonly used in symmetric encryption, and OpenSSL is often used in asymmetric encryption. In addition, in the programming often use a single hash encryption algorithm, such as md5,hash,sha1,password_hash, such as the data (usually the user Password) encryption, This encryption is not decrypted (theoretically no non-decryption algorithm, It is said that the decrypted machine takes longer to be decrypted. In general, can still use the brute force dictionary to crack and find the rainbow table way to crack, hash one-way encryption will generally have a salt value.


In a Real-world scenario, there are only data signatures that transmit the data in plaintext (which is the most), and there are data signatures and encrypted data that are used for transmission, and half of the data is rarely encrypted without data signing. 、


MCrypt encryption

First identify these concepts

algorithm name: the password algorithm supported by the MCrypt extension, the detailed list can be found in the PHP source mcrypt.php file. The algorithm supported by Mcypt is shown at the end of this article.

algorithm Mode: One of the Mcrypt_mode_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" and "stream".

algorithm Module : A module that uses Mcrypt_module_open () to open the specified algorithm and schema, which is a resource type

initial vector: a parameter to be used when encrypting, using Mcrypt_create_iv () to create from a random source

initial vector size: refers to the initial vector size of the specified Algorithm/pattern combination returned by Mcrypt_get_iv_size (). Mcrypt_create_iv () creates an initial vector based on the initial vector size.


MCrypt encryption decryption requires the following steps

Encryption:

1 Use Mcrypt_module_open () to open the corresponding module for the specified algorithm and Mode.

2 mcrypt_get_iv_size () Gets the module initial vector length, mcrypt_enc_get_iv_size ($td)

3 Create initial vector Mcrypt_create_iv () based on initial vector length

4 buffer required for initialization of encryption Mcrypt_generic_init ()

5 Encrypting Data Mcrypt_generic ()

6 End encryption, Perform cleanup work Mcrypt_generic_deinit ()


Decryption requires the following several steps

1 Initial dissolve secret module Mcrypt_generic_init ()

2 Decryption Data Mcrypt_decrypt ()

3 End decryption, Perform cleanup work Mcrypt_generic_deinit ()

4 Closing the module open at Start mcrypt_module_close


The entire decryption process is similar to the process of creating a picture, first creating a canvas resource, creating a color, filling, and finally Image_destroy.


Then take a look at the usage of several of the functions mentioned above

1.mcrypt_module_open-open the module corresponding to the algorithm and mode

Resource Mcrypt_module_open (string $algorithm, string $algorithm _directory, string $mode, string $mode _directory)

Return resource type

The parameter description is shown in table 1-1

Table 1-1

parameters
algorithm mcrypt_ciphername a constant, or the algorithm name of a string Value. See end of text
algorithm_directory algorithm The _directory parameter indicates the location of the cryptographic module. If you provide this parameter, the value you specify is Used. If you set this parameter to an empty string (""), the Mcrypt.algorithms_dir in php.ini is Used. If you do not specify this parameter, the compilation path of Libmcrypt (usually/usr/local/lib/libmcrypt) is Used.
mode mcrypt_mode_modename constants , or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" and "stream".
mode_directory algorithm_directo The RY parameter indicates the location of the encryption Mode. If you provide this parameter, the value you specify is Used. If you set this parameter to an empty string (""), the Mcrypt.modes_dir in php.ini is Used. If you do not specify this parameter, the compilation path of Libmcrypt (usually/usr/local/lib/libmcrypt) is Used.


2.mcrypt_get_iv_size-returns the initial vector size for the specified algorithm/pattern combination

int mcrypt_get_iv_size (string $cipher, string $mode)

Returns the initial vector size

You can use Mcrypt_enc_get_iv_size ($td) instead, $TD can be a resource returned by Mcrypt_module_open () as a parameter.

The parameter description is shown in table 1-2

Table 1-2

Parameters Description
Cipher A mcrypt_ciphername constant, or the algorithm name of a string Value.
Mode One of the Mcrypt_mode_modename constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" and "stream".


3.mcrypt_create_iv-creating an initial vector from a random source

String Mcrypt_create_iv (int $size [, int $source = Mcrypt_dev_urandom])

Returns the initial vector

Table 1-3

Parameters Description
Size The initial vector size. can be obtained by mcrypt_get_iv_size or mcrypt_enc_get_iv_size
Source The initial vector data source. Optional values are: mcrypt_rand (system random number generator), mcrypt_dev_random (reading data from/dev/random file) and mcrypt_dev_urandom (reading data from/dev/urandom file). In versions prior to the Windows platform, PHP 5.3.0, only Mcrypt_rand is Supported.


4.mcrypt_generic_init-initialize the required buffers for encryption

int mcrypt_generic_init (resource $td, string $key, string $iv)

If an error occurs, a negative number is returned: 3 indicates the key length is incorrect, 4 indicates a memory allocation failure, other values indicate an unknown error, and a corresponding warning message is Displayed. Returns FALSE if the incoming parameter is Incorrect.

Table 1-4

Parameters Description
Td The encryption Descriptor. Types of resources obtained by Mcrypt_module_open
Key The maximum length of the key that is obtained by calling the Mcrypt_enc_get_key_size () Function. Values that are less than the maximum length are considered illegal parameters.
iv typically, the vector size equals the packet size of the algorithm, but you should use the Mcrypt_enc_get_iv_size () function to get this Value. In ECB mode, the initial vectors are ignored, and the initial vectors must be provided in CFB,CBC,STREAM,NOFB and OFB Modes. The initial vector requirements are random and unique (no need to be secure). Encryption and decryption must use the same initial Vector. If you don't want to use the initial vector, set it to a full 0 value, but it's not recommended.


5.mcrypt_generic-encrypting data

String Mcrypt_generic (resource $td, string $data)

Returns the encrypted data

Table 1-5

Parameters Description
Td The encryption Descriptor. Types of resources obtained by Mcrypt_module_open
Data The data to encrypt


6.mdecrypt_generic-decrypting data

String Mdecrypt_generic (resource $td, string $data)

Returns the decrypted string

Note that due to data completion, the length of the returned string may not be equal to the length of the plaintext

Parameter TD Cryptographic Descriptor. The type of resource obtained by mcrypt_module_open, data is a cipher that needs to be decrypted



6.mcrypt_generic_deinit-to clean up the cryptographic modules

BOOL Mcrypt_generic_deinit (resource $td)

Parameter TD Cryptographic Descriptor. Types of resources obtained by Mcrypt_module_open

This function terminates the cryptographic module specified by the cryptographic descriptor (td), which cleans up the buffer, but does not close the Module. To turn off the cryptographic module, you need to call the Mcrypt_module_close () function yourself. (but PHP will close the Open encryption module for you at the end of the Script)


7.mcrypt_module_close-closing the Cryptographic module

BOOL Mcrypt_module_close (resource $td)

Parameter TD Cryptographic Descriptor. Types of resources obtained by Mcrypt_module_open


The following example illustrates the process of adding and decrypting

class mcryptmodel{    protected  $TD  =  ';     protected  $iv  =  ';    protected  $key  =  ';     private static  $instance  = null;    private function  __construct ($cipher, $mode, $key)  {         $this->cipher  =  $cipher;         $this->mode =  $mode;          $this->key =  $key;    }     public static function getinstance ($cipher =mcrypt_rijndael_128, $mode =mcrypt_mode_ cbc,     $key = ' h5gos1zshkz6wikn ')  {        if   (self:: $instance  == null)  {             self:: $instance &NBSp;= new self ($cipher, $mode, $key);        }         return self:: $instance;    }     function encrypt ($str)  {         $td  = mcrypt _module_open ($this->cipher, ', $this->mode, ');//open algorithm module         $ this->td =  $td;         $iv _size = mcrypt_enc_ Get_iv_size ($td);//  get vector size          $iv  = mcrypt_create_ IV ($iv _size,mcrypt_rand);//initialization vector          $this->iv =  $iv;          $num  = mcrypt_generic_init ($td, $this->key, $iv);// Initialize the encryption space         //var_dump ($num);          $encypt  = mcrypt_generic ($td, $str);//perform Encryption         mcrypt_generic_deinit ($ td); //  End encryption, Perform cleanup work         return base64_encode ($encypt );//BASE64 encoded into a string for data transfer     }    function decyrpt ($str)  {          $str  = base64_decode ($str);          $TD  =  $this->td;        mcrypt_ Generic_init ($td, $this->key, $this->iv);         $decrypt  =  mdecrypt_generic ($td, $str);         mcrypt_generic_deinit ($td);         mcrypt_module_close ($td);//close Algorithm Module          return  $decrypt     }} $m  = mcryptmodel::getinstance ();echo  $s  = $m->encrypt (' Hello '); //  output  4cnqrVkCjcr5unW0ySUdWg==echo  $m->decyrpt ($e);   //  Output  hello


MCrypt encryption is symmetric, the algorithm is public, and its security is from the secrecy of the secret key. The user can choose different algorithm names and algorithm Patterns. Commonly used algorithms are mcrypt_rijndael_128,mcrypt_des,rijndael-256, etc., the commonly used mode is CBC,ECB


The following algorithms are supported in Php:

  • Mcrypt_3des

  • Mcrypt_arcfour_iv (available only Libmcrypt > 2.4.x)

  • Mcrypt_arcfour (available only Libmcrypt > 2.4.x)

  • Mcrypt_blowfish

  • mcrypt_cast_128

  • mcrypt_cast_256

  • Mcrypt_crypt

  • Mcrypt_des

  • Mcrypt_des_compat (only available in Libmcrypt 2.2.x)

  • Mcrypt_enigma (libmcrypt > 2.4.x only available, mcrypt_crypt aliases)

  • Mcrypt_gost

  • Mcrypt_idea (not Free Algorithm)

  • mcrypt_loki97 (available only Libmcrypt > 2.4.x)

  • Mcrypt_mars (libmcrypt > 2.4.x only available, not free Algorithm)

  • Mcrypt_panama (available only Libmcrypt > 2.4.x)

  • mcrypt_rijndael_128 (available only Libmcrypt > 2.4.x)

  • mcrypt_rijndael_192 (available only Libmcrypt > 2.4.x)

  • mcrypt_rijndael_256 (available only Libmcrypt > 2.4.x)

  • Mcrypt_rc2

  • MCRYPT_RC4 (only available in Libmcrypt 2.2.x)

  • MCRYPT_RC6 (available only Libmcrypt > 2.4.x)

  • mcrypt_rc6_128 (only available in Libmcrypt 2.2.x)

  • mcrypt_rc6_192 (only available in Libmcrypt 2.2.x)

  • mcrypt_rc6_256 (only available in Libmcrypt 2.2.x)

  • Mcrypt_safer64

  • mcrypt_safer128

  • Mcrypt_saferplus (available only Libmcrypt > 2.4.x)

  • Mcrypt_serpent (available only Libmcrypt > 2.4.x)

  • mcrypt_serpent_128 (only available in Libmcrypt 2.2.x)

  • mcrypt_serpent_192 (only available in Libmcrypt 2.2.x)

  • mcrypt_serpent_256 (only available in Libmcrypt 2.2.x)

  • Mcrypt_skipjack (available only Libmcrypt > 2.4.x)

  • Mcrypt_tean (only available in Libmcrypt 2.2.x)

  • Mcrypt_threeway

  • Mcrypt_tripledes (available only Libmcrypt > 2.4.x)

  • Mcrypt_twofish (versions prior to MCRYPT 2.x, or versions available after 2.4.x)

  • mcrypt_twofish128 (twofishxxx available in new 2.x version, but not in 2.4.x Version)

  • mcrypt_twofish192

  • mcrypt_twofish256

  • Mcrypt_wake (available only Libmcrypt > 2.4.x)

  • Mcrypt_xtea (available only Libmcrypt > 2.4.x)


Encrypt and decrypt using PHP 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.