PHP Security Programming encryption Function _php Foundation

Source: Internet
Author: User
Tags crypt decrypt mcrypt md5 php and php script

The role of data encryption in our lives has become increasingly important, especially given the large number of transactions and data transmissions that occur on the web. If you are interested in adopting security measures, you will also be interested in understanding the range of security features provided by PHP. In this article, we will describe these features and provide some basic usage so that you can add security features to your application. Preparatory knowledge before detailing the security features of PHP, we need to take the time to introduce some basic knowledge of cryptography to readers who have not contacted this aspect, and if the basic concepts of cryptography are already well known, we can skip this part. Cryptography can be popularly described as the study and experiment of the addition/decryption, encryption is the conversion of understandable data to difficult to understand the process of information, decryption is to convert the information is not easy to understand the original process of information. The information that is not easy to understand is called the password, the understandable information is called the plaintext. Data encryption/decryption need a certain algorithm, these algorithms can be very simple, such as the famous Caesar code, but the current encryption algorithm is relatively more complex, some of which use existing methods can not even decipher. PHP encryption features as long as a bit of the use of non-Windows platform experience may be very familiar with the crypt (), this function is called one-way encryption function, it can encrypt some plaintext, but not the password can be converted to the original plaintext. Although this appears to be a useless feature on the surface, it is indeed widely used to ensure the integrity of the system's passwords. Because, once a one-way encrypted password falls into the hands of a third party, it is not useful because it cannot be restored to plaintext. When validating the password entered by the user, the user's input is also a one-way algorithm, if the input and stored encrypted password match, then the input message must be correct. PHP also provides the possibility of using its crypt () function to complete a one-way encryption function. I'll briefly introduce this function here: String crypt (String input_string [, string Salt]) where the input_string argument is a string that needs to be encrypted, and the second optional salt is a byte string, It can influence the encrypted cipher and further exclude the possibility of being called an estimated attack. By default, PHP uses a 2-character des jamming string, and if your system is using MD5 (which I will introduce MD5 algorithm later), it will use a 12-character jamming string. By the way, you can discover the length of the jamming string that the system will use by executing the following command: print "My system salt size is:". Crypt_salt_length; The system may also support other cryptographic algorithms. Crypt () supports four algorithms, the following is the algorithm it supports and the correspondingLength of salt parameter: algorithm salt length crypt_std_des 2-character (Default) crypt_ext_des 9-character crypt_md5 12-character beginning with 1 02/td> crypt_blowfish 16-character beginning with 102/td> uses CRYPT () to implement user authentication as an example of the CRYPT () function, considering such a situation, You want to create a PHP script that restricts access to a directory, allowing only users with the correct username and password to access the directory. I'll store the data in a table in MySQL, my favorite database. Let's start with our example of creating this table called Members: the Mysql>create table members (
->username CHAR () not NULL,
->password CHAR (not NULL),
->primary KEY (username)
->); We then assume that the following data is already stored in the table: username password Clark Kelod1c377lke Bruce Ba1t7vnz9awgk Peter paluvrwsrlz4u These encrypted passwords correspond to the codes that are Kent, Banner and Parker. Notice the first two letters of each password, because I use the following code to create a jamming string based on the first two letters of the password:.
= Substr (, 0, 2);
= Crypt (,);
And then stored in MySQL with the username. I will use the Apache password-answer authentication configuration to prompt the user for username and password, and a little-known information about PHP is that it can identify the username and password entered by the Apache password-answer system as and, I'll use these two variables in my authentication script. Take the time to read the following script carefully and pay more attention to the explanations in order to better understand the following code: The Application of Crypt () and Apache password-response verification system <?php

= "localhost";
= "Zorro";
= "hellodolly";
= "Users";

Set Authorization to False

= 0;

Verify that user has entered username and password

if (Isset () && isset ()):

Mysql_pconnect (,,) or Die ("Can" T connect to MySQL
Server! ");

mysql_select_db () or Die ("Can ' t select database!");

Perform the encryption
= Substr (, 0, 2);
= Crypt (,);

Build the query

= "Select username from members WHERE
Username = "' and
Password = ' ";

Execute the query

if (Mysql_numrows (mysql_query ()) = = 1):
= 1;
endif

endif

Confirm Authorization

if (!):

Header (' Www-authenticate:basic realm= ' Private ');
Header (' http/1.0 401 Unauthorized ');
Print "are unauthorized to enter";
Exit

else:

Print "This is the secret data!";

endif

?> above is a simple authentication system that verifies user access rights. When using crypt () to protect important confidential information, keep in mind that the crypt () used in the default state is not the safest, only for systems with less security requirements, and if high security performance is required, I will need the algorithm that I have described later in this article. Next I'll introduce another PHP-supported function ━━md5 (), this function uses the MD5 hashing algorithm, which has several interesting uses to mention: mixing a mixed function can transform a variable-length information into an output with fixed-length mixed, also known as "Information Digest". This is useful because a fixed-length string can be used to check the integrity of the file and verify the digital signature and user authentication. Because it is suitable for php,php built-in MD5 () hybrid functions will convert a variable-length information to 128-bit (32-character) Information Digest. An interesting feature of the hybrid is that it is not possible to get the original plaintext by analyzing the mixed information, because the result is not dependent on the original plaintext content. Even changing only one character in a string will make the MD5 hybrid algorithm compute two distinct results. Let's first look at the contents of the table and the corresponding results: using MD5 () mixed string <?php
= "This is some the message I just wrote";
= MD5 ();
Print "Hash:";
?> Result: hash:81ea092649ca32b5ba375e81d8f4972c Note that the result is 32 characters in length. Take a look at the table below, where the value has a slight change: use MD5 () to mix a slightly changed string <?php
Note that an S is missing from the message
= "This is some mesage I just wrote";
= MD5 ();
Print "Hash2: <br/><br/>";
?> results: hash2:e86cf511bd5490d46d5cd61738c82c0c can find that although the two results are 32 characters in length, a slight change in the plaintext changes the result greatly, so the mixed and MD5 () A function is a good tool for checking small changes in data. Although crypt () and MD5 () are useful, they are limited in function. In the following sections, we will introduce two very useful PHP extensions called MCrypt and Mhash, which will greatly expand the PHP user's choice of encryption. Although we explained the importance of one-way encryption in the above section, sometimes we may need to encrypt the password data back to the original data, fortunately, PHP in the form of MCrypt Extension Library to provide this possibility. Mcrypt Mcrypt 2.5.7 Unix | Win32 Mcrypt 2.4.7 is a powerful encryption algorithm extension library that includes 22 algorithms, including the following: Blowfish RC2 safer-sk64 xtea Cast-256 RC4 safer-sk128 DES rc4-i V. Serpent Enigma Rijndael-128 threeway Gost Rijndael-192 TripleDES LOKI97 Rijndael-256 twofish panamasaferplus installation: in superscript Quasi-PHP packages do not include mcrypt, so you need to download it, download the address: ftp://argeas.cs-net.gr/pub/unix/mcrypt/. After downloading, compile with the following method and expand it in PHP: Download the MCrypt package. Gunzipmcrypt-x.x.x.tar.gz Tar-xvfmcrypt-x.x.x.tar./configure--disable-posix-threads make make install CD to your PHP di Rectory. ./configure-with-mcrypt=[dir] [--other-configuration-directives] make made install of course, depending on your requirements and the relationship between PHP installation and Internet Server Software, The above process may require appropriate modifications. The advantage of using MCrypt MCrypt is not only that it provides more encryption algorithms, but also that it canAdd/decrypt processing, in addition, it also provides 35 kinds of functions to process data. Although the details of these functions are beyond the scope of this article, I would like to briefly introduce a few typical functions. First, I'll explain how to use the MCrypt extension library to encrypt data, and then explain how to use it to decrypt. The following code demonstrates this process by encrypting the data, displaying the encrypted data in the browser, and restoring the encrypted data to the original string, which is displayed on the browser. Use MCrypt to add and decrypt data <?php

Designate string to is encrypted
= "Applied cryptography, by Bruce Schneier, is
A wonderful cryptography reference. ";

Encryption/decryption Key
Key = "Four score and twenty years ago";

Encryption algorithm
= mcrypt_rijndael_128;

Create the initialization vector for added security.
= Mcrypt_create_iv (Mcrypt_get_iv_size (,
MCRYPT_MODE_ECB), Mcrypt_rand);

Output Original String
Print "Original string: <p>";

Encrypt
= Mcrypt_encrypt (, key,
, MCRYPT_MODE_CBC,);

Convert to hexadecimal and output to browser
Print "Encrypted string:". Bin2Hex (). <p> ";

= Mcrypt_decrypt (, key,
, MCRYPT_MODE_CBC,);

Print "decrypted string:";

?> executing the above script will produce the following output: Original string:applied cryptography, by Bruce Schneier, is a wonderful cryptography. Encrypted string:02a7c58b1ebd22a9523468694b091e60411cc4dea8652bb8072 34fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b C89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 bfbab5e Decrypted string:applied cryptography, by Bruce Schneier, is a wonderful cryptography. The two most typical functions in the above code are Mcrypt_encrypt () and Mcrypt_decrypt (), and their use is obvious. I used the "Telegraph cipher This" mode, MCrypt provides several encryption methods, because each encryption method has the specific characters that can affect the security of the password, so each pattern needs to understand. The Mcrypt_create_iv () function may be more interesting to readers who have no access to a cryptographic system, although a thorough explanation of this function is beyond the scope of this article, but I still refer to the initialization vector it creates (hence, iv), This always allows each piece of information to be independent of each other. Although not all patterns require this initialization variable, PHP gives a warning message if the variable is not supplied in the required pattern. Mhash Extension Library http://sourceforge.net/projects/mhash/0.8.3 version of the Mhash extension Library supports 12 kinds of hybrid algorithms, carefully check Mhash v.0.8.3 header file mhash.h can know that it supports the following hybrid algorithm: CRC32 HAVAL160 MD5 crc32b HAVAL192 RIPEMD160 GOST HAVAL224 SHA1 HAVAL128 HAVAL256 TIGER Installation like MCrypt, Mhash is not included in the PHP package, for non-Windows users, the following is the installation process: Download Mhash extension Library gunzipmhash-x.x.x.tar.gz tar-xVfmhash-x.x.x.tar./configure make make install CD <php directory >./configure-with-mhash=[dir] [-- Other-configuration-directives] make made install like MCrypt, depending on how PHP is installed on the Internet Server Software, you may need to configure mhash differently. For Windows users, there is a good PHP package, including the Mhash extension library, in http://www.php4win.de. Just download and unzip it, and then install it according to the instructions in the Readme.first document. Using Mhash to mix information is very simple, take a look at the following example: <?php
= Mhash_tiger;
= "These are the directions to the secret fort. Two steps left, three steps right, and Cha Chacha. ";
= Mhash (,);
Print "The hashed message is". Bin2Hex ();
?> execution of this script will result in the following output: The hashed message is 07a92a4db3a4177f19ec9034ae5400eb60d1a9fbb4ade461 uses the Bin2Hex () function here to Is the output that is convenient for us to understand, because the result of the mixing is binary format, in order to be able to convert it into an easy-to-understand format, it must be converted to hexadecimal format. It should be noted that the integrated is a one-way function, the result is not dependent on input, so you can publicly display this information.      This strategy is typically used to allow users to compare downloads and system administrator files to ensure the integrity of the file. Mhash also has some other useful functions. For example, I need to output the name of an mhash-supported algorithm, because all of the algorithms supported by Mhash start with mhash_, so you can do this by executing the following code: <?php
= Mhash_tiger;
Print "This data has been hashed with the". Mhash_get_hash_name (). " hashing algorithm. ";
The output obtained by?> is: This data has been hashed with the TIGER hashing algorithm. One last question about PHP and encryption The last important thing to note about PHP and encryption is that the data transferred between the server and the client is not secure during transmission! PHP is a server-side technology that cannot prevent data from leaking during transmission. Therefore, if you want to achieve a complete security application, it is recommended to choose Apache-ssl or other security server layout. Conclusion This article describes one of PHP's most useful features, ━━ data encryption, which not only discusses the PHP built-in crypt () and MD5 () cryptographic functions, but also discusses powerful extensions for data encryption ━━mcrypt and Mhash. At the end of this article, I need to point out that a truly secure PHP application should also include a secure server, because PHP is a server-side technology, so it does not guarantee data security when data is transmitted by the client to the server side. Editor: Xiao Li

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.