PHP Security Programming encryption Function _php Tutorial

Source: Internet
Author: User
Tags crypt mcrypt php software
The status of data encryption in our lives has become increasingly important, especially given the large amount of data that is being traded and transmitted over the network. If you are interested in adopting security measures, you will also be interested in understanding a range of security features provided by PHP. In this article, we'll cover these features and provide some basic usage so that you can add security features to your application. Pre-knowledge before we go into the details of PHP's security features, we need to take a moment to introduce some basic knowledge about cryptography to readers who have not been exposed to this aspect, and if you are already familiar with the basic concepts of cryptography, you can jump over this part. Cryptography can be popularly described as the study and experiment of encryption and decryption, which is the process of converting understandable data into difficult-to-understand data, and decryption is the process of converting understandable data into original understandable data. The information that is not easy to understand is called the password, and the understandable information is called the plaintext. Data encryption/decryption requires a certain algorithm, these algorithms can be very simple, such as the famous Caesar code, but the current encryption algorithm to be relatively more complex, some of which use the existing methods even can not be deciphered. PHP encryption function As long as there is a bit of experience with non-Windows platform people may be quite familiar with crypt (), this function is called one-way encryption function, it can encrypt some plaintext, but not the ability to convert the password to the original plaintext. Although it appears to be a useless feature on the surface, it is widely used to ensure the integrity of the system's passwords. Because one-way encrypted passwords fall into the hands of third parties and are not much useful because they cannot be reverted to plaintext. When validating the user input password, the user's input is also a one-way algorithm, if the input and stored encrypted password matching, the input message must be correct. PHP also provides the possibility of using its crypt () function to complete a one-way encryption function. I will briefly describe this function here: String crypt (String input_string [, string Salt]) where the input_string parameter is a string that needs to be encrypted, and the second optional salt is a byte string, It can affect the cryptographic cipher, further eliminating the possibility of being called an estimate attack. By default, PHP uses a 2-character des interference string, and if your system is using MD5 (I'll introduce the MD5 algorithm later), it will use a 12-character interference string. By the way, you can find the length of the interfering 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 length of the corresponding salt parameterDegree: Algorithm salt length crypt_std_des2-character (Default) Crypt_ext_des9-charactercrypt_md512-character beginning with 102/td >crypt_blowfish16-character beginning with 102/td> using CRYPT () to implement user authentication as an example of the CRYPT () function, consider a situation where You want to create a PHP script that restricts access to a directory, allowing only users who can provide the correct user name and password to access the directory. I'm going to store the data in a table in my favorite database, MySQL. Let's begin our example by creating this table called the Members: Mysql>create Table Members (
->username CHAR () not NULL,
->password CHAR (+) not NULL,
->primary KEY (username)
Then, we assume that the following data is already stored in the table: User name password clarkkelod1c377lkebruceba1t7vnz9awgkpeterpaluvrwsrlz4u These encrypted passwords correspond to the plaintext of Kent, Banner and Parker. Note the first two letters of each password, because I used the following code to create a disturbance string based on the first two letters of the password:.
= Substr (, 0, 2);
= Crypt (,);
And then it's stored in MySQL with the username. I will use the Apache password-answer authentication configuration prompts the user to enter a user name and password, a little-known information about PHP is that it can be Apache password-answering system input username and password to identify as and, I'll use these two variables in the authentication script. Take some time to read the following script carefully, and pay more attention to the explanations in order to better understand the following code: Crypt () and Apache's password-Response verification System application
= "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" 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 "You is unauthorized to enter this area.";
Exit

else:

Print "This is the secret data!";

endif

?> above is a simple authentication system that verifies the user's access rights. When using crypt () to protect important confidential information, remember that the crypt () used in the default state is not the safest and can only be used in systems with lower security requirements, and if high security performance is required, the algorithm that I will describe later in this article is required. Here I will introduce another PHP-supported function, ━━MD5 (), which uses the MD5 hashing algorithm, which has several interesting usages worth mentioning: a mixed-use function can transform a variable-length information into a fixed-length, mixed-over output, also known as an "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 as well as user authentication. Since it is suitable for php,php the built-in MD5 () mixed function will convert a variable-length information into a 128-bit (32-character) Information Digest. One interesting feature of the mixing is that the original plaintext cannot be obtained by analyzing the mixed information, because the result of the mixing is not dependent on the original plaintext content. Even changing only one character in a string will make the MD5 mixed algorithm calculate two distinct results. Let's start by looking at the contents of the table and its corresponding results: using the MD5 () mixed string = "This is some a message that I just wrote";
= MD5 ();
Print "Hash:";
?> Result: hash:81ea092649ca32b5ba375e81d8f4972c Note that the length of the result is 32 characters. Take a look at the table below, where the value has a slight change: use MD5 () to mash up a slightly changed string Note that one of the missing s in the message
= "This was some mesage that I just wrote";
= MD5 ();
Print "HASH2:

";
?> results: hash2:e86cf511bd5490d46d5cd61738c82c0c can be found that although the length of the two results is 32 characters, a small change in the plaintext results in a great change in the result, so the mixed and MD5 () Functions are a good tool for checking small changes in data. Although crypt () and MD5 () are useful, they are subject to certain limitations in their functionality. In the following section, we will cover two very useful PHP extensions called MCrypt and Mhash, which will greatly expand the choice of encryption for PHP users. Although we have explained the importance of one-way encryption in the above section, sometimes we may need to restore the password data to the original data after encryption, fortunately, PHP provides this possibility in the form of a mcrypt extension library. Mcryptmcrypt 2.5.7 Unix | Win32 Mcrypt 2.4.7 is a powerful cryptographic algorithm extension library that includes 22 algorithms, including the following algorithms: Blowfish RC2 safer-sk64 xtea Cast-256 RC4 safer-sk128 DES Rc4-iv Serpent Enigma Rijndael-128 threeway Gost Rijndael-192 TripleDES LOKI97 Rijndael-256 twofish panamasaferplus Wake installation : MCrypt is not included in the standard PHP package, so it needs to be downloaded and the download address is: ftp://argeas.cs-net.gr/pub/unix/mcrypt/. After downloading, follow the methods below to compile 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 do install CD to your PHP di Rectory. ./configure-with-mcrypt=[dir] [--other-configuration-directives] make make install of course, according to your requirements and PHP installation with the Internet Server Software relationship, The above procedure may need to be modified as appropriate. The advantage of using Mcryptmcrypt is not only that it provides more cryptographic algorithms, but also that it can add/decrypt data, and itIt also provides 35 functions for processing data. Although the details of these functions are beyond the scope of this article, I would like to give a brief introduction to a few typical functions. First, I'll show you how to encrypt the data using the MCrypt extension library, and then explain how to use it for decryption. The following code demonstrates this process by encrypting the data, then displaying the encrypted data on the browser and restoring the encrypted data to the original string and displaying it on the browser. Use MCrypt to add and decrypt data
Designate string to be 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:

";

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

Convert to hexadecimal and output to browser
Print "Encrypted string:". Bin2Hex (). "

";

= Mcrypt_decrypt (, key,
, MCRYPT_MODE_CBC,);

Print "decrypted string:";

?> execution of the above script will produce the following output: Original string:applied cryptography, by Bruce Schneier, is a wonderful cryptography reference. Encrypted string:02a7c58b1ebd22a9523468694b091e60411cc4dea8652bb8072 34FA06BBFB20E71ECF525F29DF58E28F3D9BF541F7EBCECF62B C89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 Bfbab5edecrypted string:applied cryptography, by Bruce Schneier, is a wonderful cryptography reference. The two most typical functions in the above code are MC Rypt_encrypt () and Mcrypt_decrypt (), their use is obvious. I use the "Telegraph cipher" mode, MCrypt provides several encryption methods, because each encryption method can affect the password security of certain characters, so each mode needs to understand. The Mcrypt_create_iv () function may be more interesting to readers who have not contacted the password system, although a thorough explanation of this function is beyond the scope of this article, but I will still mention the initialization vectors it created (hence, iv), This has always allowed 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 provided 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 mixed algorithms, carefully examine Mhash v.0.8.3 header file mhash.h can know that it supports the following mixed algorithm: CRC32 HAVAL160 MD5 crc32b HAVAL192 RIPEMD160 GOST HAVAL224 SHA1 HAVAL128 HAVAL256 TIGER Installation like MCrypt, Mhash is not included in the PHP software 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 do install CD ./configure-with-mhash=[dir] [--other-configuration-directives] make make install like MCrypt, based on how PHP is installed on the Internet server Software, Additional configuration of the Mhash may be required. For Windows users, there is a good PHP package in http://www.php4win.de that includes the Mhash extension library. Just download and unzip, then install according to the instructions in the Readme.first document. Using Mhash to mash up information is very simple, take a look at the following example: = Mhash_tiger;
= "These is the directions to the secret fort. The steps left, the 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 used here Bin2Hex () The purpose of the function is to facilitate our understanding of the output, because the result of the mixing is binary format, in order to be able to convert it into a format that is easy to understand, it must be converted to hexadecimal format. It is important to note that the mash is a one-way feature and the result is not dependent on input, so this information can be displayed publicly. This strategy is typically used to allow users to compare downloaded files and files provided by the system administrator to ensure file integrity. Mhash also has some other useful functions. For example, I need to output the name of an algorithm supported by Mhash, because the names of all the algorithms supported by Mhash begin with Mhash_, so you can do this by executing the following code: = Mhash_tiger;
Print "This data have been hashed with the". Mhash_get_hash_name (). " hashing algorithm. ";
The output from?> is: This data have been hashed with the TIGER hashing Algorithm. One of the last things to note about PHP and encryption is that the last important thing to note about PHP and encryption is that the data that is transferred between the server and the client is not secure during transmission! PHP is a server-side technology that does not prevent data from being compromised during transmission. Therefore, if you want to implement a complete security application, it is recommended to choose APACHE-SSL or other secure server placement. Conclusion This article describes one of the most useful features of PHP ━━ data encryption, not only discusses PHP's built-in crypt () and MD5 () cryptographic functions, but also discusses the powerful extension libraries ━━mcrypt and Mhash for data encryption. 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 when the data is transferred from the client to the server, it does not guarantee the security of the data. Editor: Xiao Li

http://www.bkjia.com/PHPjc/314395.html www.bkjia.com true http://www.bkjia.com/PHPjc/314395.html techarticle The status of data encryption in our lives has become increasingly important, especially given the large amount of data that is being traded and transmitted over the network. If you are interested in adopting security measures ...

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