php-cryptography algorithm and its application-symmetric cipher algorithm

Source: Internet
Author: User
Tags decrypt mcrypt php source code

Transferred from: http://www.smatrix.org/bbs/simple/index.php?t5662.html

//////////////////////////////////////////////////////////////////////////////
Directory
1. PHP hash function and its application
2. Symmetric cipher algorithm in PHP and its application
3. PHP's public key cryptography algorithm and its application
///////////////////////////////////////////////////////////////////////////////

2 symmetric cipher algorithm in PHP and its application
I've been trying to write the cryptography algorithm and its application in PHP for some time, but there are a lot of trivial things to do, so I want to be able to make it clear in a language that is popular rather than scholarly.
2.1 What is a symmetric cipher algorithm
The hash function we put before is not a real cipher algorithm, but a function that generates a message digest. Because a password system needs to have five components (ciphertext, plaintext, encryption algorithm, decryption algorithm, key). The key to distinguishing between symmetric and asymmetric cryptographic algorithms is whether the decryption key is equal to the encryption key, and if it is equal, it is symmetric and unequal is asymmetric. Like Des,aes are symmetric cipher algorithms, and RSA,ECC are asymmetric public-key cryptography algorithms. In general, symmetric cipher algorithms and decryption is faster, usually for data encryption, and asymmetric public key encryption algorithm and decryption speed is slow, usually used for digital signature and construction of complex cryptographic protocols. It's absurd to say that a public-key encryption algorithm is better and safer than a symmetric encryption algorithm, which is more useful than talking about your hands and feet.
2.2 What is called symmetric cipher algorithm encryption mode
This is a lot of developers do not very clear things, after all, most PHP developers may not have been exposed to the professional training in cryptography, so see PHP related functions feel daunting, overwhelmed. The so-called encryption mode is the method of encrypting any length of message using the cipher algorithm. Normally symmetric cipher algorithms provide at least four basic modes of operation, two of which are block mode (ECB and CBC), and two are stream modes (CFB and OFB). To make a popular analogy, the cipher algorithm function is like a machine, the plaintext is like the raw material, the machine cannot process all the plaintext at once, then the strategy of block mode is to group the plaintext, then follow certain rules into the machine to do processing, then get a set of ciphertext. The ECB pattern is to divide messages into separate blocks, each with the same algorithm and key encryption (such as using DES), with no association between blocks and blocks. And CBC is to divide the message into separate blocks, but when the encryption, do a bit of hands and feet, so that the next piece of ciphertext and the previous piece of ciphertext has a relationship between the block encryption before and the previous piece of ciphertext to be different or operation, and then in the same algorithm and key encryption, because the first piece of plaintext does not have a piece of ciphertext Called the initialization vector. While the CFB and OFB modes consider plaintext as binary streams, which are actually chunked, they all require an initialization vector, generate pseudo-random binary streams continuously, and then separate or operate with plaintext, and whether ciphertext participates in operations is the difference between CFB and OFB. The details of the working mode are not well-described in words, interested in the Book of Cryptography (Security matrix forum A lot, whatever the next one has).
2.3 Symmetric cipher algorithm functions in PHP
Each version of PHP provides the corresponding symmetric cryptographic algorithm functions, so PHP developers do not need to own a cottage, please believe that the provided symmetric cryptographic algorithm function is definitely more powerful than your own design. So far, there are a variety of colors of the guest (and ancestral) is said to be able to break a cryptographic algorithm for a few minutes or seconds, in fact, this is a misunderstanding, in addition to the Snow forum to see a few directly against the key of the brute force to crack the instance, I rarely seen on the network mathematically can compromise a cryptographic algorithm of people. The system or software was cracked because the cryptographic algorithm was improperly used or the attacker bypassed the cryptographic algorithm mechanism. PHP's main symmetric cryptographic algorithm functions are derived from the MCrypt function family. Of course this family of functions is an optional part of PHP and needs to be downloaded libmcrypt-x.x.tar.gz and configured in php.ini. You can use Phpinfo () to see if your configured environment supports these functions.

MCrypt support: enabledversion:  2.5.8  Api No: 20021217  supported ciphers:  cast-128 gost rijndael-128 twofish arcfour cast-256 loki97 rijndael-192 saferplus wake Blowfish-compat des Rijndael-2 Serpent Xtea blowfish Enigma RC2 TripleDES  supported modes:  CBC CFB Ctr ECB NCFB NOFB OFB stream  


Supported ciphers is listed in the support algorithm, algorithm a lot, very good very powerful, where Rijndael is the beginning of AES, so PHP does not have AES is Miushun. Next we describe how to properly use PHP's symmetric cryptographic algorithm functions. First we see this function Mcrypt_module_open, the prototype is:

string string string string mode_directory)


The function is actually to create a working environment that uses a symmetric cryptographic algorithm (it's important to understand that if you've learned Windows programming, this idea is ubiquitous), Tell PHP what algorithm (the first parameter) to use, where the algorithm path is (the second argument), What mode of operation (the third parameter) is used, and where the working mode describes the path (the fourth parameter). In practice, we don't normally need to set the second and fourth parameters. Now let's look at an example:

<?PHP$key= "Security Matrix";//secret key    $input= "Mathmatica sounds very terrible!";//plaintext//encryption    $TD= Mcrypt_module_open (' rijndael-256 ', ' ', ' CBC ', ');//Create an encrypted environment    $iv= Mcrypt_create_iv (Mcrypt_enc_get_iv_size ($TD), Mcrypt_rand);//with CBC mode, we need an initialization vector IV. Mcrypt_generic_init ($TD,$key,$iv);//initializes the encryption algorithm, and when the algorithm mode is the ECB, it automatically ignores the IV    $encrypted _out_data= Mcrypt_generic ($TD,$input);//Performing EncryptionMcrypt_generic_deinit ($TD);//Releasing cryptographic algorithm resourcesMcrypt_module_close ($TD);//turn off the encryption environment and release resources    Echo"Clear Text is:$input"; Echo' <br> '; EchoThe key is:$key"; Echo' <br> '; Echo"Ciphertext is:$encrypted _out_data"; Echo' <br> '; //decryption, because $IV is not cleared, so we can continue to use this. Be sure to keep it in practice .    $TD= Mcrypt_module_open (' rijndael-256 ', ' ', ' CBC ', ');//Create an encrypted environmentMcrypt_generic_init ($TD,$key,$iv); $decrypted _out_data=mdecrypt_generic ($TD,$encrypted _out_data); Mcrypt_generic_deinit ($TD);//Releasing cryptographic algorithm resourcesMcrypt_module_close ($TD);//turn off the encryption environment and release resources        Echo' <br> '; EchoThe key is:$key"; Echo' <br> '; Echo"Clear Text is:$decrypted _out_data";


This source code I added the comments and the PHP manual is slightly different, mainly because I want to make people understand more. Here are a few functions, the first one is Mcrypt_create_iv, this is used to create a random initialization vector IV, four basic modes, except the ECB, must have initialization vector IV. The Mcrypt_generic_init function is used to initialize a cryptographic algorithm object, including a handle to a specific algorithm, a key, and an initialization vector. When the algorithm pattern is the ECB, the function automatically ignores the initialization vector IV. Next, use Mcrypt_generic to perform the encryption. Use Mcrypt_generic_deinit and Mcrypt_module_close to release the environment after encryption is complete. This process is very similar to the process of using device resources under Windows programming. It is important to note that because the IV generation uses random numbers, each time it is different, it also causes the ciphertext to be different. Therefore, in addition to the ECB mode, the other three models have to write down the IV in order to decrypt. Decryption process and encryption process is the same, but the function mcrypt_generic replaced with mdecrypt_generic, please note, do not dazzle, pay attention to their handwriting differences, the former is encrypted, the latter is decryption. This process is the standard procedure for using symmetric cryptographic algorithms in PHP.
There are some very unfamiliar cipher algorithms in PHP, such as GOST, unless you specialize in cryptographic algorithms, few people will know the exact contents of this algorithm. We can use the following PHP algorithm information function to understand an algorithm:


Here's how to use it:

<?PHP$TD= Mcrypt_module_open (Mcrypt_blowfish, ', ' ECB ', '); EchoMcrypt_enc_get_algorithms_name ($TD). "\ n"; EchoMcrypt_enc_get_block_size ($TD). "\ n"; EchoMcrypt_enc_get_iv_size ($TD). "\ n"; EchoMcrypt_enc_get_key_size ($TD). "\ n"; EchoMcrypt_enc_get_modes_name ($TD). "\ n"; //Results: Blowfish 8 8 ECB


In addition to the above usage in PHP, there is a use of encryption and decryption. relies on functions Mcrypt_encrypt and Mcrypt_decrypt, which are used for encryption, which is used for decryption. Its function prototypes are:

string string string string string string IV]) string string string string string string IV])


It is easy to see that the parameters of the two functions are exactly the same, and in fact only the same can be done to encrypt and decrypt normally. The difference between this usage and the previous function usage is that these two functions use all of the algorithm information as their own parameters, and people accustomed to traditional PHP development will find this easier to use. Take a look at the code first:

<?PHP$iv _size= Mcrypt_get_iv_size (mcrypt_rijndael_256, MCRYPT_MODE_CBC);//Gets the IV vector size of the algorithm in OFB mode    $iv= Mcrypt_create_iv ($iv _size, Mcrypt_rand);//Create an initialization IV vector    $key= "Security Matrix";//secret key    $plaintext= "You should arrive here in eight clock";//plaintext    $ciphertext= Mcrypt_encrypt (mcrypt_rijndael_256,$key,$plaintext, MCRYPT_MODE_CBC,$iv);//perform encryption directly    Echo"Clear Text is:$plaintext.<br> Ciphertext is:$ciphertext"; $outtext= Mcrypt_decrypt (mcrypt_rijndael_256,$key,$ciphertext, MCRYPT_MODE_CBC,$iv);//Perform decryption    Echo"<br>"; Echo"The decrypted plaintext is:$outtext<br> "; //Result://Clear Text is: You should arrive here in eight clock. Ciphertext is: P mayfly ~ credential ' mh! BL desired ' Es?? {? e Jin * yc¬ wentao áreal c RC biweekly j Xie K 躕 "蟸 v advise//decrypted clear text is: You should arrive here in eight clock


In addition to the above two comprehensive usages, PHP provides four cryptographic functions that directly specify cryptographic modes MCRYPT_CFB (), MCRYPT_CBC (), MCRYPT_ECB (), and MCRYPT_OFB (), which are almost identical to the prototypes of the four functions. In the case of MCRYPT_CBC (), the prototype is as follows:

string int string string int string IV]) string string string string int string IV])


Where the first parameter specifies the algorithm, the second parameter specifies the key, the third parameter specifies the data (according to the following mode determines whether it is clear or ciphertext), the fourth parameter mode specifies whether the encryption operation or decryption operation, the fifth parameter is optional, If you need IV, be sure to iv. or look at an example, you will find it so simple:

<?PHP$key= "Security Matrix";$text= "Fleshwound is a farmer,deadly wounded";//plaintext$ctext= MCRYPT_ECB (Mcrypt_3des,$key,$text, Mcrypt_encrypt);//Encrypt$ptext= MCRYPT_ECB (Mcrypt_3des,$key,$ctext, Mcrypt_decrypt);//decryptionEchoClear text$text<br> Ciphertext:$ctext<br> decryption after clear text:$ptext"//Result://Clear text: Fleshwound is a farmer,deadly wounded//ciphertext: Backup 剢 gsxe?+? v?3 khada:? 2 pull 哣 磀 毄 +?//decrypted Clear text: Fleshwound is a farmer,deadly wou nded



Well, write for a few hours, finally introduced the symmetric cipher algorithm in PHP, in fact, we will find that the use or is very simple, not more difficult than writing a paging function, if you can be used in their own projects locally, will make system security greatly improved. and smart children's shoes can be found from here to the PHP source code self-decryption Code generation method (more flexible than Zend), of course, can also be used to do bad things, to achieve page-level deformation of the Trojan, specific methods I do not introduce. The next topic is the public key cryptography algorithm in PHP, I will try to use PHP's cryptography application in a popular way to gradually lead in depth.

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.