Preparatory knowledge
Before you introduce the security features of PHP, we need to take a time to introduce some basic knowledge about the cryptography. If you have been very familiar with the basic concept of cryptography, you can jump through this part. .
Cryptography can be easily described as a process and experiment of add / decryption. Encryption is a process of converting easy-to-understand data into unhabilitation data. Decryption is a process that will not be understood into the original easy-to-understand data. The information that is not easy to understand is called a password, and the information that is easy to understand is called a clear code.
Data add / decryption requires a certain algorithm, which can be very simple, such as the famous Caesar code, but the current encryption algorithm is much more complicated, some of which can be used to decipher by the existing method.
PHP encryption function
As long as some people using non-Windows platform experience may be quite familiar with Crypt (), this function completes the function called a single-way encrypted, it can be encrypted, but it is not possible to convert the password into the original codes. Although it seems to be a function of nothing from the surface, it is indeed widely used to ensure the integrity of the system password. Because, one-way encrypted passwords have fallen into third-party people, because they cannot be reduced as plaintext, there is no big use. When verifying the password entered by the user, the user's input is also a one-way algorithm, and if the input is matched to the stored encrypted password, the input handy is correct.
PHP also provides the possibility of using its CRYPT () function to complete the one-way encryption function. I will briefly introduce this function here:
String crypt (String Input_String [, String Salt])
The input_string parameter is a string that needs to be encrypted. The second optional SALT is a bit string that can affect the encrypted dark code and further exclude the likelihood that is called pre-counting attacks. By default, PHP uses a 2-character DES interference string, if your system uses MD5 (I will introduce the MD5 algorithm later), it will use a 12-character interference string. By the way, you can find the length of the interference string to use by performing the following command:
Print "My System Salt Size IS:". Crypt_salt_length;
The system may also support other encryption algorithms. Crypt () supports four algorithms, the following is the length of the algorithm it supports and the corresponding SALT parameters:
Algorithm SALT length
Crypt_std_des 2-character (default)
Crypt_ext_des 9-character
Crypt_md5 12-Character Beginning with $ 1 $
Crypt_blowfish 16-Character Beginning With $ 2 $
Implement user authentication with CRYPT ()
As an example of a Crypt () function, consider such a case, you want to create a PHP script to restrict access to a directory, only allowing users to access this directory for users to provide the correct username and password. I will store the information in a table I like database MySQL. Below we start our examples to create this 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 this table:
Username Password
Clark Kelod1c377LKE
Bruce ba1t7vnz9awgk
Peter Paluvrwsrlz4u
These encrypted passwords correspond to Kent, Banner, and Parker, respectively. Pay attention to the first two letters per password, because I use the following code, create an interference string according to the first two letters of the password: $ enteredpassword.
$ SALT = Substr ($ EnteredPassword, 0, 2);
$ userpswd = crypt ($ ENTEREDPassword, $ SALT);
// $ USERPSWD then stores with the user name in MySQL
I will use Apache's password-Answer authentication configuration prompting users to enter username and password, a freshly known information about PHP information is, it can identify user names and password entered by Apache to $ PHP_AUTH_USER and $ PHP_AUTH_PW, I will use these two variables in the authentication script. Take some time carefully read the following scripts, pay more attention to the explanation in order to better understand the following code:
Crypt () and Apache password - application of response verification system
PHP
$ host = "localhost";
$ user = "zorro";
$ PSWD = "Hellodolly";
$ 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
Server! ");
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) == 1):
$ authorization = 1;
Endif;
Endif;
// Confirm Authorization
IF ($ authorization):
HEADER ('www-authenticate: Basic realm = "private");
HEADER ('http / 1.0 401 unauthorized');
Print "you are unauthorized to enter this area.";
EXIT;
Else:
Print "this is the secret data!";
Endif;
?>
The above is a simple authentication system that verifies user access rights. When using CRYPT () protects important confidential information, remember that Crypt () used in the default state is not the safest, and can only be used in a system with lower security requirements, if a higher security is required Performance requires me to introduce the algorithm described later in this article. Below I will introduce another PHP support function ━━md5 (), this function uses the MD5 hash algorithm, which is a very interesting usage worth mentioning:
Mixed
A mixed function can convert an variable length to have an output of a fixed length and is also referred to as "information". This is very useful because a fixed length string can be used to check the integrity of the file and verify digital signatures and user authentication. Since it is suitable for PHP, the PHP built-in MD5 () mixed function will convert a variable length information to 128-bit (32 characters) information. One interesting feature of mixing is that it is not possible to get the original clear code by analyzing the mixed information, because the result of mixed results is not dependent on the original clear content. Even if only one character in a string is changed, the MD5 mixed algorithm will also calculate two distinct results. Let's first look at the contents of the table below and its corresponding results:
Use MD5 () mixed strings
PHP
$ msg = "this is some message what i Just wrote";
$ ENC_MSG = MD5 ($ MSG);
Print "Hash: $ ENC_MSG";
?>
result:
Hash: 81ea092649ca32b5ba375e81d8f4972c
Note that the length is 32 characters. Let's take a look at the table below, where the value of $ msg has a little change:
Use MD5 () to mix a slightly changing string
PHP
// Note that there is a little in Message.
$ msg = "this is some mesage what i Just wrote";
$ ENC_MSG = MD5 ($ MSG);
Print "Hash2: $ ENC_MSG
";
?>
result:
Hash2: e86cf511bd5490d46d5cd61738c82c0c
It can be found that although the length of the two results is 32 characters, a little change in the clear text makes a big change, so the mixed and MD5 () functions are a very good change in the data in the data. Tool of.
Although Crypt () and MD5 () are useful, both are functionally limited. In the following section, we will introduce two very useful PHP extensions called Mcrypt and Mhash, which will greatly expand PHP users in encryption.
Although we explained the importance of unidirectional encryption in the above section, sometimes we may need to restore the password data into the original data after encryption, and the PHP provides this in the form of the Mcrypt expansion library. possibility.
Mcrypt
Mcrypt 2.5.7 UNIX | Win32
Mcrypt 2.4.7 is a powerful encryption algorithm extension, 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:
Do not include Mcrypt in a standard PHP package, so you need to download it, the downloaded address is: ftp: //Argeas.cs-net.gr/pub/unix/mcrypt/. After downloading, compile according to 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 directory.
./configure -with-mcrypt = [DIR] [- Porther-configuration-directives]]
Make
Make Install
Of course, according to your requirements and PHP installation relationship with the Internet server software, the above process may need to make appropriate modifications.
Use mcrypt
The advantage of Mcrypt is more than just the encryption algorithm it provides, but it is also that it can add / decrypt the data, in addition, it also provides 35 functions for processing data. Although the detailed introduction to these functions has exceeded the scope of this article, I still have to make a brief introduction on several typical functions.
First, I will introduce how to encrypt the data using the Mcrypt extension library, and then describe how to use it to decrypt. The following code is demonstrated on this process, first of all, encrypts the data, then displays the encrypted data on the browser, and restores the encrypted data to the original string, display it on the browser.
Use Mcrypt to add data to data, decrypt
PHP
// 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";
?>
Executing 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 bfbab5e
Decrypted string: Applied Cryptography, by Bruce Schneier, IS A Wonderful Cryptography Reference.
Two most typical functions in the above code are mcrypt_encrypt () and mcrypt_decrypt (), and their use is obvious. I used the "Telegraph Password" mode, Mcrypt provides several encryption methods. Since each encryption method has specific characters that can affect password security, each mode needs to be understood. For readers who have not contacted password systems, it may be more interested in mcrypt_create_iv () functions, although thorough explanation for this function has exceeded the scope of this article, but I will still mention the initialization vector it created. (HENCE, IV), this vector can make each information independent of each other. Although this initialization variable is required not all modes, the PHP will give a warning message if this variable is provided in the required mode.
Mhash extension library
http://sourceforge.net/projects/mhash/
The Mhash extension of the 0.8.3 version supports 12 mixed algorithms, carefully checks the header file Mhash.h of Mhash V.0.8.3, which 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 package. For non-Windows users, the following is the installation process:
Download Mhash Expansion Library
gunzipmhash-x.x.x.tar.gz
Tar -xvfmhash-x.x.x.tar
./configure
Make
Make Install
CD
./configure -with-mhash = [dir] [- other-configuration-directives]]
Make
Make Install
Like Mcrypt, according to the installation of PHP on the Internet server software, other configurations may be required to make Mhash.
For Windows users, there is a good PHP package including the Mhash extension library. Just download and decompress, then install it according to the instructions in the readme.first document.
Use Mhash
Mixed information is very simple, look at the example below:
PHP
$ hash_alg = mhash_tiger;
$ Message = "The SECRET. Two Steps Left, Three Steps Right, And Chacha."
$ has Hashed_Message = Mhash ($ hash_alg, $ message);
Print "The Hashed Message IS". BIN2HEX ($ HASHED_MESSAGE);?>
Executing this segment program will get the following output:
The Hashed Message IS 07A92A4DB3A4177F19EC9034AE5400EB60D1A9FB4ADE461
It is convenient for us to understand the output of $ hashed_message, because the result of mixing is a binary format, in order to convert it into an easy-to-understand format, must convert it into a hexadecimal format. .
It should be noted that mixed is a one-way function, and the result is not dependent on input, so this information can be displayed. This strategy is usually used to allow users to compare files provided by download files and system administrators to ensure the integrity of the file.
Mhash has other useful functions. For example, I need to output a name of the algorithm supported by Mhash, because the names of all algorithms supported by Mhash are starting with Mhash_, so they can complete this task by executing the following code:
PHP
$ hash_alg = mhash_tiger;
Print "this Data Has Been Hashed with The" .Mhash_get_hash_name ($ hashed_message). "" Hashing Algorithm. "
?>
The resulting output is:
This Data Has Been Hashed with the Tiger Hashing Algorithm.
One problem about PHP and encryption needs to pay attention to
About PHP and encryption Need to pay attention to the last important issue is that data transmitted between servers and clients is not safe during transmission! PHP is a server-side technology that cannot prevent data from being leaked during transmission. Therefore, if you want to implement a complete secure application, it is recommended to use Apache-SSL or other security server arrangements.
in conclusion
This article introduces one of the most useful features of PHP, not only discusses the built-in Crypt () and MD5 () encryption functions built in PHP, but also discusses powerful expansion library for data encryption, McRYPT and Mhash. In this article, I need to point out that a real secure PHP application should also include a secure server, because PHP is a server-side technology, so when the data is transmitted by the client to the server, it cannot Guarantee the security of the data.
Author: Liu Yanqing
Posted on 2004 07