PHP Security programming-encryption function-PHP Tutorial

Source: Internet
Author: User
Tags crypt mcrypt md5 hash php software
Encryption Function of PHP Security programming. Data encryption has become more and more important in our lives, especially considering the large amount of data that has been traded and transmitted over the Internet. If you are interested in using security measures, data encryption is becoming more and more important in our lives, especially considering the large volume of transactions and transmitted data on the network. If you are interested in using security measures, you will be interested in learning a series of security functions provided by PHP. In this article, we will introduce these features and provide some basic usage so that you can add security features to your application software. Before giving a detailed introduction to PHP's security functions, we need to spend some time introducing the basic cryptography knowledge to those who have not been familiar with this aspect, if you are familiar with the basic concepts of cryptography, you can skip this part. Cryptography can be widely described as the research and experiment on encryption/decryption. encryption is a process of converting easy-to-understand data into easy-to-understand data, decryption is the process of converting obscure data into original understandable data. An obscure document is called a password, and an easy-to-understand document is called a plaintext. Data encryption/decryption requires certain algorithms. these algorithms can be very simple, such as the famous Caesar code. However, the current encryption algorithm is much more complex, some of these methods cannot be decrypted even by using the existing methods. The encryption function of PHP may be quite familiar to crypt () as long as a person who has experience on non-Windows platforms. this function completes the one-way encryption function, which can encrypt some clear codes, however, the password cannot be converted to the original plaintext. Although on the surface this seems useless, it is indeed widely used to ensure the integrity of the system password. Because, once a one-way encryption password falls into the hands of a third party, it is useless because it cannot be restored to plain text. When verifying the password entered by the user, the user's input is also a one-way algorithm. if the input matches the stored encrypted password, the entered message must be correct. PHP also provides the possibility of using its crypt () function to implement one-way encryption. Here I will briefly introduce this function: string crypt (string input_string [, string salt]) where the input_string parameter is the string to be encrypted, the second available salt is a single-digit string, which can affect the encrypted password and further eliminate the possibility of a pre-computing attack. By default, PHP uses a two-character DES interference string. if your system uses MD5 (I will introduce the MD5 algorithm later ), it uses a 12-character interference string. By the way, you can run the following command to find the length of the interference string to be used by the system: print "My system salt size is :". CRYPT_SALT_LENGTH; the system may also support other encryption algorithms. Crypt () supports four Algorithms. below are the algorithms it supports and the length of the corresponding salt parameter: 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> uses crypt () to implement user authentication as an example of the crypt () function, you want to create a PHP script to restrict access to a directory and only allow users with the correct username and password to access this directory. I will store materials in a table in my favorite MySQL database. The following is an example of creating a TABLE called members: mysql> create table members (
-> Username CHAR (14) not null,
-> Password CHAR (32) not null,
-> Primary key (username)
->). Then, we assume that the following data has been stored in the table: username and password clarkkeloD1C377lKEbruceba1T7vnz9AWgkpeterpaLUvRWsRLZ4U. the encryption passwords correspond to kent, banner, and parker. Note the first two letters of each password. this is because I used the following code to create an interference string based on the first two letters of the password :.
= Substr (, 0, 2 );
= Crypt (,);
// Then it is stored together with the user name in MySQL. I will use the Apache password-response authentication configuration to prompt the user to enter the user name and password. a little-known information about PHP is, it can recognize the username and password entered by the Apache password-response system as the sum. I will use these two variables in the authentication script. Take some time to carefully read the following script and pay more attention to the explanation to better understand the following code: crypt () and Apache 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 members WHERE
Username = ''AND
Password = ''";

// Execute the query

If (mysql_numrows (mysql_query () = 1 ):
= 1;


// Confirm authorization

If (! ):

Header ('www-Authenticate: Basic realm = "Private "');
Header ('http/1.0 401 unauthorized ');
Print "You are unauthorized to enter this area .";


Print "This is the secret data! ";


?> The above is a simple authentication system that verifies user access permissions. When using crypt () to protect important confidential information, remember that the crypt () used by default is not the safest and can only be used in systems with low security requirements, if you need high security performance, you need the algorithms I will introduce later in this article. Next, I will introduce another function supported by PHP, namely, Handler digest md5 (). This function uses the MD5 hash algorithm. it has several interesting usage values: A mixed-length function can convert a variable-length information into an output with a fixed-length mixed-length, also known as "Information Digest ". This is useful because a fixed-length string can be used to check file integrity and verify digital signatures and user identity authentication. Because it is suitable for PHP, PHP's built-in md5 () mixed encoding function converts a variable-length information to a 128-bit (32 characters) Digest. An interesting feature of mixed encoding is that the original plaintext cannot be obtained by analyzing the information after the mixed encoding, because the result after the mixed compilation is not dependent on the original plaintext content. Even if you change only one character in a string, the MD5 mixed encoding algorithm calculates two completely different results. First, let's look at the content in the table below and the corresponding results: Use md5 () to mix strings = "This is some message that I just wrote ";
= Md5 ();
Print "hash :";
?> Result: hash: 81ea092649ca32b5ba375e81d8f4972c. Note that the result length is 32 characters. Let's take a look at the table in "tables", where the value changes slightly: Use md5 () to mix a slightly changed string. // Note that one s is missing in the message
= "This is some mesage that I just wrote ";
= Md5 ();
Print "hash2:

?> Result: hash2: e86cf109bd5490d46d5cd61738c82c0c can be found that although the two results are all 32 characters in length, a slight change in the description greatly changes the results. therefore, mixed encoding and md5 () functions are a good tool for checking small changes in data. Both crypt () and md5 () are useful, but both are limited in functionality. In the following section, we will introduce two very useful PHP extensions called Mcrypt and Mhash, which will greatly expand the encryption options of 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 through the Mcrypt Extension Library. McryptMcrypt 2.5.7 Unix | Win32 Mcrypt 2.4.7 is a powerful encryption algorithm Extension Library, which 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: the standard PHP package does not include Mcrypt, so you need to download it, download address: . After the download, follow the following method to compile and expand it to PHP: Download the Mcrypt package. Gunzipmcrypt-x.x.x.tar.gz tar -xvfmcrypt-x.x.x.tar. /configure -- disable-posix-threads make install cd to your PHP directory .. /configure-with-mcrypt = [dir] [-- other-configuration-directives] make install. of course, according to your requirements and the relationship between PHP and Internet server software during installation, the above process may need to be modified as appropriate. McryptMcrypt not only provides many encryption algorithms, but also supports data encryption/decryption. In addition, it provides 35 Data processing functions. Although the detailed introduction to these functions is beyond the scope of this article, I would like to give a brief introduction to several typical functions. First, I will introduce how to use the Mcrypt Extension Library to encrypt data, and then how to use it for decryption. The following code demonstrates this process. first, encrypt the data, display the encrypted data in the browser, and restore the encrypted data to the original string, display it in a browser. Use Mcrypt to encrypt 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

// Create the initialization vector for added security.
= Mcrypt_create_iv (mcrypt_get_iv_size (,

// Output original string
Print "Original string:


// Encrypt
= Mcrypt_encrypt (, key,

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


= Mcrypt_decrypt (, key,

Print "Decrypted string :";

?> Execute the above script to generate the following output: Original string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference. encrypted string: encryption bfbab5eDecrypted string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference. the two most typical codes above Type functions are mcrypt_encrypt () and mcrypt_decrypt (). Their usage is obvious. I used the "Telegraph cipher book" mode. Mcrypt provides several encryption methods. since each encryption method has specific characters that can affect password security, you need to understand each mode. Readers who have never touched on the password system may be more interested in the mcrypt_create_iv () function, although the thorough explanation of this function is beyond the scope of this article, but I will still mention the initialization vector (hence, iv) it creates, which can always make each piece of information independent of each other. Although not all modes require this initialization variable, PHP will give a warning if this variable is not provided in the required mode. Mhash Extension Library The version of the Mhash extension library supports 12 mixed encoding algorithms. check the header file Mhash of mhash v.0.8.3 carefully. h. it supports the following mixed encoding algorithm: CRC32 HAVAL160 MD5 CRC32B HAVAL192 RIPEMD160 GOST haval1_sha1 HAVAL128 HAVAL256 TIGER. like Mcrypt, Mhash is not included in the PHP software package, for non-Windows users, the following is the installation process: Download the Mhash Extension Library gunzipmhash-x.x.x.tar.gz tar -xvfmhash-x.x.x.tar. /configure make install cd . /Configure-with-mhash = [dir] [-- other-configuration-directives] make install is the same as Mcrypt, according to the PHP installation method on Internet server software, other Mhash configurations may be required. For Windows users, the has a good PHP package including the Mhash Extension Library. Download and decompress the package, and install the package according to the instructions in readme. first. It is very easy to use Mhash to mix and compile information. refer to the following example: = 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 ();
?> Run this script to get The following output: The hashed message is 07a92a4db3a%7f19ec9034ae5400eb60d1a9fbb4ade461 The purpose of using The bin2hex () function here is to facilitate our understanding of The output, this is because the result of mixed encoding is a binary format. to convert it into an easy-to-understand format, you must convert it to a hexadecimal format. It should be noted that the mixed editing is a one-way function, and the result does not depend on the input. Therefore, this information can be publicly displayed. This policy is usually used to allow users to download files and files provided by the system administrator to ensure file integrity. Mhash has other useful functions. For example, I need to output the name of an algorithm supported by Mhash. because the names of all algorithms supported by Mhash start with MHASH _, you can execute the following code to complete this task: = MHASH_TIGER;
Print "This data has been hashed with the". mhash_get_hash_name (). "hashing algorithm .";
?> The output is: This data has been hashed with the TIGER hashing algorithm. the last important question about PHP and encryption is that the data transmitted between the server and the client is insecure! PHP is a server-side technology that cannot prevent data leaks during transmission. Therefore, if you want to implement a complete security application, we recommend that you use Apache-SSL or other security server layout. Conclusion This article introduces encryption of cipher data, one of the most useful functions of PHP. it not only discusses the built-in encryption functions of crypt () and md5 () in PHP, we also discussed the powerful extended libraries used for data encryption, including cipher Mcrypt and Mhash. At the end of this article, I need to point out that a truly secure PHP application should also include secure servers. because PHP is a server-side technology, when data is transmitted from a client to a server, it cannot guarantee data security. Responsible editor: Xiao Li

Bytes. If you are interested in using 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: 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.