php-cryptography algorithm and its application-hash function

Source: Internet
Author: User
Tags crypt hmac md5 hash sha1 sha1 hash

Transfer from

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
Preface: So many years have been concentrated on the cultivation of internal strength, did not write something on the Internet, security matrix as a rare in the country with cryptography and information security theory research as the characteristics of academic technology research organization, in the domestic promotion of cryptography application is our responsibility, although this road is more difficult and long, but always need people to do. I plan to several major mainstream scripting language separately elaborated, the system summarizes, strives for the common script developer and the Netizen to be able to understand. This is the first article on PHP, the following assumption that the reader already has the basic knowledge of PHP.
1. PHP hash function and its application
1.1 What is a hash function
The hash function, also known as the hash function (hash function), is called a hash function, which is a function of changing any long input message string into a fixed long output string. This output string is called the hash value of the message (or called a hash value). Generally used to generate a message digest, the integrity of the data message test. Strictly speaking, hash function is not a cryptographic algorithm, because it is one-way irreversible. A hash function has the following characteristics: (1) The input length is arbitrary, and the output length is fixed, the length should be long enough to resist the birthday attack (please Baidu for birthday attacks). (2) For each given input, the forward calculation of the output is the hash value is very easy, but the reverse to find the collision difficult.
Hash function is mainly used for completeness check and improve the validity of digital signature, it has very important application in the cipher protocol, and there are many mature schemes at present. For specific cryptography knowledge, go to the security matrix to download some books to see.
There are two common hash functions (hash functions):
(1), MD5 (Message Digest algorithm 5): is a RSA data security company developed a one-way hashing algorithm, MD5 is widely used, can be used to set different lengths of data blocks to operate into a 128-bit value;
(2, SHA (Secure Hash algorithm) This is a newer hashing algorithm that can generate a 160-bit value for any length of data operation.
At present theoretically MD5 and SHA have been cracked, but in practical application is not so simple, as long as reasonable application is always feasible. In addition, the following are also considered functions of hashing functions.
(1), MAC (Message authentication code): Messaging authentication codes, is a one-way function that uses keys, which can be used to authenticate files or messages between the system or the user. An HMAC (key hashing method for message authentication) is an example of this function.
(2), CRC (Cyclic redundancy Check): Cyclic redundancy check code, CRC verification due to simple implementation, the ability to detect errors, is widely used in various data validation applications.
(3), self-produced cottage version and hash function based on some symmetric encryption algorithm.
1.2 hash function in PHP and its application
The most common hashing functions in PHP are the following:
MD5 (), Md5_file (), SHA1 (), Sha1_file ().
In fact, there are more powerful and flexible crypt and Mhash series. First of all, let's start with a simple and useful look at an instance:

<?PHP$str= "Security matrix is a website about Cryptograhy."; $HASHMD 5=MD5($str); $hashsha 1=SHA1($str); Echo"MD5 hash value is:".$HASHMD 5; Echo' <br> '; Echo"SHA1 hash value is:$hashsha 1"; //The final result is://md5 hash value is:c4558a37e61eb1db03f7270d4f674ae6//SHA1 hash value is:d10155e45624bf84b4d1fdf4e6e47 E067B7A4E1A

Obviously, our string passes these two functions to get a series of irregular 16 binary sequences. Note that the sequence produced by SHA1 is 8 characters more than MD5, in total SHA1 this is because SHA1 is a 160-bit hash, and MD5 is a 128-bit hash. Cryptography refers to the bit is the number of binary bits, a 16 binary accounted for 4 bits, so SHA1 is 16 binary 40 bits, MD5 is 16 binary 32 bits. The prototypes of these two functions are:

string string BOOL Raw_output]) string string bool Raw_output])

One of the optional parameters, Raw_output, is a Boolean type, and the default is False, and if you write 1 or True here, you can guarantee that the value is a true expression. The output is a true message digest. See the same example:

<?PHP$str= "Security matrix is a website about Cryptograhy."; $HASHMD 5=MD5($str, 1); $hashsha 1=SHA1($str, 1); Echo"MD5 hash value is:".$HASHMD 5; Echo' \<br> '; Echo"SHA1 hash value is:$hashsha 1"; //The final result is://MD5 hash value is: 腢?? Arm? OGJ rigidity//SHA1 hash value is:? U 銿 $ 縿 Chimneys ~ {ZN

Obviously, this is a bit like the Martian text, the message digest when stored in MySQL, sometimes because the character set can appear character problem. Generally we only use the default, in the form of 16 binary output, storage convenience. In general, MD5 and SHA1 use the most occasions is to verify the user password occasions. The user's password is usually MD5 or SHA1 processed and placed in the database to reduce the risk of exposing real password information in the event of SQL injection or data table access. However, due to the use of the standard MD5 algorithm, the hash value of the common password can easily be poor, so the actual search for a collision may be relatively easy. Online There are many such MD5 hash collisions of the query site. To deal with this, we can use a few variants or a salt-based Mac when using it, and it's best to use SHA1. Here's an example:

<? PHP     $passwd= "13455564432";     $salt= "DFDASAFGR4VTRGRRGF";     $str=$passwd. $salt ;     $HASHMD 5=MD5(MD5($str).  $salt);       Echo $HASHMD 5 // results: bc052554e38b588df52594176a148b8b

Now let's talk about Md5_file (), Sha1_file (). Obviously, this is used to calculate the hash value of the given file name. The function prototypes are as follows:

string string BOOL Raw_output]) string string bool Raw_output])

The meaning and usage of the parameters is the same as the previous MD5 (), SHA1 (). We can look at an example:

<? PHP     $filename = ' 1.txt ';     $hash Md5_file ($filename);     Echo $hash // result E0a7a59e58c7b138e850b8055fba27da

These two functions can be used to determine whether their program files have been tampered with, such as whether to embed a Trojan horse. Discuz Forum Source code has a check function, use this implementation. In addition, it can be used to construct complex mathematical validation algorithms to prevent others from cracking PHP programs that require authorization. As long as the program is modified, the hash value of its file is basically changed. Shell The script code of course this is difficult for a typical programmer. The general application of these are basically enough, which is supported by the default PHP. Next, let's look at the Mac and CRC.
The main function is Mhash (), which, in layman's words, is a hash function with a key. Why bring a key, in fact, this improvement is mainly to prevent the hash function of online violence to crack and improve anti-collision ability. The function prototypes are as follows:

string int string string key])

Because this belongs to the extension module, so to use Mhash (), you need to compile PHP when you add a configuration, in the PHP configuration, adding--with-mhash[=dir]. If not, there will be "Fatal error:call to undefined function ...", the first parameter of this function is the hash algorithm pattern we want to use, consisting of some pre-defined algorithm patterns, the hash value of each algorithm pattern is different, Among the most commonly used are the following:

mhash_md5mhash_sha1mhash_haval256   // The Haval series algorithms support a wide range of output lengths, from 128-256  ///RIPEMD series algorithms also support multiple output lengths, from 128-256

The second parameter is the string to which we want to calculate the hash value, and the third parameter is the key. In addition, the HMAC system has other functions as follows:

mhash_count-------generates a secure password hash value,--computes the hash value

To illustrate their usage, let's take a look at examples:

<?PHP$input= "Security Matrix"; $hash= Mhash (MHASH_MD5,$input); Echo"The hash is".Bin2Hex($hash) . "<br/>\n";//The result: the hash ise6cfee2c4530b72d7f8f4b010fa80a00    $hash= Mhash (MHASH_MD5,$input, "Smatrix"); Echo"The HMAC is".Bin2Hex($hash) . "<br/>\n";//The result: The HMAC is d3e7983ba7bdb7c7d0150e056d2c5017     EchoMhash_count (). " &LT;BR/>\n "; $hash=mhash_ripemd160; EchoMhash_get_hash_name ($hash)." <br/>\n ";//gets the algorithm name for the RIPEMD160     EchoMhash_get_hash_name (24). " <br/>\n ";//let's see what it provides for the 24th algorithm pattern, get the algorithm name, for RIPEMD256     EchoMhash_get_block_size (24). " <br/>\n ";//gets the hash value length generated by the 24th algorithm pattern, with the result of 32,32*8=256, a character of 8 bits

MHASH_KEYGEN_S2K is a particularly good thing, it is suggested that PHP developers can use it instead of the traditional MD5 to handle user passwords, at least for these MD5 collision retrieval site online failure. The MHASH_KEYGEN_S2K () function specifies the parameters of the 1-hash algorithm pattern, specifying the parameter 3-random salt, and generating a pseudo-random pickled password on the original password parameter 2 to generate bytes length (parameter 4). The so-called salt, is to add noise interference in the information, destroy some of its semantic characteristics. The prototype of this function is:

string int string string int bytes)

Below, let's look at the specific usage:

 <? php      $password  = "Security Matrix"   $salt  = "F34iffffffffj4"   $hash  = mhash_ripemd160;      $bytes  =160;  echo  mhash_keygen_s2k (," Span style= "color: #800080;" > $password ,  $salt ,  $bytes ); //  yield 160 of the pickled password//result://毉 V9 edged B??  韔 a dysprosium x K 藎 Ù 壥 VD 磌? ┕? concurred (J Iゎ 忲 "?" Yangzhou "Kiln 1〧//" fight. Taekwondo]? 欭: 躎?    3 浹 からご Connection 3-がj Basket 9&?v1 懏 ^ incurred 3 鄡 turtle-? neptunium 轐 P ' xxj;? Estate  

It is worth noting that, in practice, the best different user passwords use different salts, the same salt always makes people not very relieved, in general, we do not need to bring a salt library, randomly generated one and need to keep, otherwise the user password will be error when the time. Here I can give a feasible solution, so that salt and user password within the relevant, eliminating the trouble of memory salt, as follows:

<? PHP     $password = "Security Matrix";     $salt MD5 ($password);     $hash = mhash_ripemd160;     $bytes=160;     Echo $hash $password $salt $bytes // produces a pickled password of length 160

Now we introduce the last one-way hash function crypt, which many people would mistakenly recognize as symmetric cryptographic functions, is not, in fact, the next chapter I will specifically discuss PHP symmetric encryption algorithm. Now let's look at the prototype of this function:

string string string Salt])

This function uses parameters, the first of which is the string we need to hash the value of, and the next optional parameter is salt. If you don't fill it out, it will use the default salt. However, I do not recommend using the default, the default may appear some special problems in the application. For example, due to the change of salt, the final hash value is different when the user's password is pickled, which causes the authentication user to fail. This function, if you look at the PHP manual, may be a little dizzy and find that the function does not know where to define its hash algorithm. In fact, serious analysis will find that it is based on the length and format of the salt to decide which algorithm to use, which is a very strange way. Let's take a look at the example.

<?PHPif(Crypt_std_des = = 1) {    Echo' Standard DES: '.Crypt(' ', ' RL '). "<br>\n";}//when the salt is two characters, the built-in hashing algorithm uses the Standard DES construct, which is the crypt_std_des modeif(Crypt_ext_des = = 1) {    Echo' Extended DES: '.Crypt(' ', ' _j9. Rasm '). "<br>\n";}//when the salt is nine characters, the built-in hashing algorithm uses the Extended des construct, which is the crypt_ext_des modeif(Crypt_md5 = = 1) {    Echo' MD5: '.Crypt(' ', ' $1$rasmusle$ '). "<br>\n";}//when salt starts with $1$ and 12 characters, the built-in hashing algorithm uses MD5, which is CRYPT_MD5 modeif(Crypt_blowfish = = 1) {    Echo' Blowfish: '.Crypt(' ', ' $2a$07$rasmuslerd...........$ '). "<br>\n";}//The built-in hashing algorithm uses the BLOWFISH construct, which is the crypt_blowfish mode/result://standard des:rls0yk8/sarn6//extended when the salt starts with $2a$ or $2$ and 16 characters. DES: _j9. RASM6CQPLVIS6PO//MD5: $1$rasmusle$z4lislfbi/oo4nyaxr4eb///blowfish: $2a$07$rasmuslerd ...... WNBDKPDTWJSNGFORY7IYGVP8XWLRCNI

The hashing algorithm in PHP is basically finished, and from the above discussion, the Mhash function system is more flexible and safer to use. Crypt is more eccentric, and few people use it very often. The basic hashing function is most convenient to use, but the problem is also more, easy to be poor lift. Of course, not every IDC will load Mhash in its PHP module, and we need to understand the server environment when we develop the application. It is generally possible to see through the information in the Phpinfo function:
Mhash support     Enabled
Mhash API version      emulated support
is written here, the next section is PHP's symmetric cipher algorithm and its application. I hope that you can use more mature cryptography solutions in development, rather than one of their own innovation cottage.

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: 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.