PHP data encryption
Published in: China PHP Alliance www.phpx.com Authors / Source: ccidnet / ccidnet.com Popularity: 16667
Source: www.ccidnet.com Data Encryption is increasingly important in our lives, especially considering a large number of transactions and lots of data that occurred on the network. If you are interested in using security measures, you will definitely understand a range of security features provided by PHP. In this article, we will introduce these features to provide some basic usage so that you can add security features to your application. Preliminary knowledge before introducing PHP security features, we need to take a time to introduce some readers who have not been exposed to this aspect. If the basic concept of cryptography is already very familiar, you can jump over 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. The data is added / 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 not be deciphered by using existing methods. PHP encryption functionality as long as some people who use non-Windows platform experiences may be quite familiar with Crypt (), this function completes the function called a single-way encrypted, but it can be encrypted, but it cannot be converted to the original Code. 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. 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]) where the input_string parameter is a string that needs to be encrypted, the second optional SALT is a bit string, which can affect encryption The dark code further eliminates 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 be used by executing the following command: Print "My System Salt size is:". Crypt_salt_length; system may also support other encryption algorithms. crypt () supports four algorithms, the following is the length of the algorithm and the corresponding salt parameters it supports: 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 $ with CRYPT () Implementing User Authentication as an example of a Crypt () function, consider such a case, you want to create a PHP script limit to a directory access, only allowing users to provide the correct username and password Access this directory. I will store the information in a table I like database MySQL.
Below we started our example with the table known as 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 Kelod1c3777lke Bruce Ba1t7vnz9awgk Peter Paluvrwsrlz4u These encrypted passwords correspond to Kent, Banner, and Parker. 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 password - Acknowledge authentication configuration prompt users to enter username and password, a freshly known PHP The information is that it can identify the username and password entered by Apache's password-answering system as $ PHP_AUTH_USER and $ PHP_AUTH_PW, I will use this 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 - response verification system Application Php $ 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 ($ PAP_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 (mysql_query ($ query)) == 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 i S 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: Mixing a mixed function can put a variable length The information is transformed into an output having 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 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 ";?> Results: Hash: 81EA092649CA32B5BA375E81D8F4972C Note that the length of 32 characters. 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, a few S $ msg in Message = "This is some mesage"; $ ENC_MSG = MD5 ($ msg); Print "Hash2: $ ENC_MSG
";> Result: Hash2: E86CF511BD5490D46D5CD61738C82C0C can be found, despite two results The length is 32 characters, but a small change in the plain text makes a big change, so the mixed and MD5 () functions is a good tool for checking the slight change in the data. 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 expansion 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: Do not include Mcrypt in the 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-xxxtar.gz tar -xvfmcrypt-xxxtar ./configure --disable-posix-threads make make install cd to your PHP directory. ./configure -with-mcrypt = [dir] [--other-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.
The advantage of using Mcrypt McRYPT is not only more encryption algorithms therebet, but it is also that it can add / decrypt the data, in addition, it provides a function of 35 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, the data is encrypted, then display the encrypted data on the browser, and restores the encrypted data to the original string, display it on the browser. Use Mcrypt for data encryption, decryption "; $ decrypted_string = mcrypt_decrypt ($ cipher_alg, $ key, $ encrypted_string, MCRYPT_MODE_CBC, $ iv); print? "Decrypted string: $ decrypted_string";> the implementation of the above script produces the following Output: Original String: Applied Cryptography, By Bruce Schneier, IS A Wonderful Cryptography Reference. Encrypted String: 02a7c58b1ebd22a9523 468694b091e60411cc4dea8652bb8072 34fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b c89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 bfbab5e Decrypted string:. Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference code above two functions are the most typical mcrypt_encrypt () and mcrypt_decrypt (), their use will become apparent. 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 http://sourceforge.net/projects/mhash/0.8.3 version of Mhash extension supports 12 mixed algorithms, carefully check the header file Mhash.h of Mhash V.0.8.3, it can be found, it supports the following Mixing algorithm: CRC32 HAVAL160 MD5 CRC32B HAVAL192 RIPEMD160 GOST HAVAL192 SHA1 HAVAL128 HAVAL256 TIGER Installation icon Mcrypt, Mhash does not include in the PHP package, for non-Windows users, the following is the installation process: Download Mhash Extension GunzipMhash- XXXTAR.GZ TAR -XVFMHASH-XXXTAR ./configure make make install CD