This article provides a detailed analysis of PHP Data Encryption. For more information, see
This article provides a detailed analysis of PHP Data Encryption. For more information, see
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, 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 some basic cryptographic knowledge to those who have never 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.
Anyone who has experience using a non-Windows platform may be familiar with crypt (). This function is called one-way encryption and can encrypt some plain 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 user's entered password, 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])
The input_string parameter is the string to be encrypted, and the second available salt is a single-digit string. It 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 the following algorithms and the length of the corresponding salt parameter:
Algorithm Salt Length
CRYPT_STD_DES 2-character (Default)
CRYPT_MD5 12-character beginning with $
CRYPT_BLOWFISH 16-character beginning with $
Use crypt () for User Authentication
As an example of the crypt () function, you want to create a PHP script to restrict access to a directory, only users with the correct username and password can 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
The encrypted 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:
$ Salt = substr ($ enteredPassword, 0, 2 );
$ UserPswd = crypt ($ enteredPassword, $ salt );
// $ UserPswd is stored in MySQL together with the user name
I will use Apache password-Response Authentication configuration to prompt the user to enter the user name and password. A little-known information about PHP is, it recognizes the username and password entered by the Apache password-response system as $ PHP_AUTH_USER and $ PHP_AUTH_PW. 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:
Application of password-response verification system for crypt () and Apache
$ Host = "localhost ";
$ User = "zorro ";
$ Pswd = "hell odolly ";
$ Db = "users ";
// Set authorization to False
$ Authorization = 0;
// Verify that user has entered username and password
If (isset ($ PHP_AUTH_USER) & isset ($ PHP_AUTH_PW )):
Mysql_pconnect ($ host, $ user, $ pswd) or die ("Can't connect to MySQL
Mysql_select_db ($ db) or die ("Can't select database! ");
// Perform the encryption
$ Salt = substr ($ PHP_AUTH_PW, 0, 2 );
$ Encrypted_pswd = crypt ($ PHP_AUTH_PW, $ salt );
// Build the query
$ Query = "SELECT username FROM members WHERE
Username = '$ PHP_AUTH_USER' AND
Password = '$ encrypted_pswd '";
// Execute the query
If (mysql_numrows (mysql_query ($ query) = 1 ):
$ Authorization = 1;
// Confirm authorization
If (! $ Authorization ):
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 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, the built-in md5 () Mixed encoding function of PHP converts a variable-length information to a 128-bit (32 characters) information 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 table content and the corresponding results:
Use md5 () to mix strings
$ Msg = "This is some message that I just wrote ";
$ Enc_msg = md5 ($ msg );
Print "hash: $ enc_msg ";
Note that the result length is 32 characters. Let's take a look at the table below the values, where the value of $ msg has a slight change:
Use md5 () to mix a slightly changed string
// Note that one s is missing in the message
$ Msg = "This is some mesage that I just wrote ";
$ Enc_msg = md5 ($ msg );
Print "hash2: $ enc_msg
It can be found that although the length of the two results is 32 characters, a slight change in the text makes a great change in the results. Therefore, mixed encoding and md5 () function is a good tool for checking small changes in data.
Although crypt () and md5 () are both useful and Hong Kong virtual hosts, 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.
Mcrypt 2.5.7 Unix | Win32
Mcrypt 2.4.7 is a powerful extension library for encryption algorithms. It 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)
The standard PHP package does not contain Mcrypt. Therefore, you need to download it at: ftp://argeas.cs-net.gr/pub/unix/mcrypt /. After downloading the SDK, compile it as follows and expand it to PHP:
Download the Mcrypt package.
./Configure -- disable-posix-threads
Cd to your PHP directory.
./Configure-with-mcrypt = [dir] [-- other-configuration-directives]
Of course, according to your requirements and the relationship between PHP installation and internet server software, the above process may need to be modified.
Mcrypt 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 and then display the encrypted data and website space on the browser, the encrypted data is restored to the original string and displayed in the browser.
Use Mcrypt to encrypt and decrypt data
// Designate string to be encrypted
$ String = "Applied Cryptography, by Bruce Schneier, is
A wonderful cryptography reference .";
// Encryption/decryption key
$ Key = "Four score and twenty years ago ";
// Encryption Algorithm
$ Cipher_alg = MCRYPT_RIJNDAEL_128;
// Create the initialization vector for added security.
$ Iv = mcrypt_create_iv (mcrypt_get_iv_size ($ cipher_alg,
MCRYPT_MODE_ECB), MCRYPT_RAND );
// Output original string
Print "Original string: $ string
// Encrypt $ string
$ Encrypted_string = mcrypt_encrypt ($ cipher_alg, $ key,
$ String, MCRYPT_MODE_CBC, $ iv );
// Convert to hexadecimal and output to browser
Print "Encrypted string:". bin2hex ($ encrypted_string )."
$ Decrypted_string = mcrypt_decrypt ($ cipher_alg, $ key,
$ Encrypted_string, MCRYPT_MODE_CBC, $ iv );
Print "Decrypted string: $ 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: 201734fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b 108bfbab5e
Decrypted string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.
The two most typical functions in the above Code 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
Version 0.8.3's Mhash extension Library supports 12 mixed Encoding algorithms. Check the Mhash v.0.8.3 header file mhash. h carefully. It supports the following mixed Encoding algorithms:
CRC32 HAVAL160 MD5
CRC32B HAVAL192 RIPEMD160
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
./Configure-with-mhash = [dir] [-- other-configuration-directives]
Like Mcrypt, other Mhash configurations may be required based on the PHP installation method on Internet server software.
For Windows users, there is a good PHP software 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 mix and compile information. Let's look at the following example:
$ Hash_alg = MHASH_TIGER;
$ Message = "These are the ctions to the secret fort. Two steps left, three steps right, and cha chacha .";
$ Hashed_message = mhash ($ hash_alg, $ message );
Print "The hashed message is". bin2hex ($ hashed_message );
Execute this script to get the following output:
The hashed message is 07a92a4db3a4247f19ec9034ae5400eb60d1a9fbb4ade461
Here, the purpose of using the bin2hex () function is to help us understand the output of $ hashed_message. This is because the result of mixed encoding is in binary format, in order to convert it into an easy-to-understand format, it must be converted to the 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 documents 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:
$ Hash_alg = MHASH_TIGER;
Print "This data has been hashed with the". mhash_get_hash_name ($ hashed_message). "hashing algorithm .";
The output is as follows:
This data has been hashed with the TIGER hashing algorithm.
The last thing to note about PHP and Encryption
The last important issue to note about PHP and encryption is that the data transmitted between the server and the client is insecure during transmission! 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.
This article introduces encryption of encryption in zookeeper, 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.