PHP Data Encryption _php

Source: Internet
Author: User
Keywords Encryption data PHP algorithm polygon need function
Tags crypt mcrypt
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's encryption function
As long as there is a bit of experience with non-Windows platform 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'm going to briefly describe this function here:

String crypt (String input_string [, string salt])
The input_string parameter is a string that needs to be encrypted, and the second optional salt is a bit string that 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;
Other cryptographic algorithms may also be supported by the system. Crypt () supports four algorithms, the following is the length of the algorithm it supports and the corresponding salt parameter:

Algorithm Salt length
Crypt_std_des 2-character (Default)
Crypt_ext_des 9-character
Crypt_md5 12-character beginning with $
Crypt_blowfish 16-character beginning with $

Implementing user authentication with crypt ()
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 start with an example of creating this table called the members:

Mysql>create TABLE Members (
->username CHAR () not NULL,
->password CHAR (+) not NULL,
->primary KEY (username)
);

We then assume that the following data is already stored in the table:

User name password
Clark Kelod1c377lke
Bruce Ba1t7vnz9awgk
Peter Paluvrwsrlz4u

These encrypted passwords correspond to the plaintext of Kent, banner, and Parker respectively. 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:

$enteredPassword.
$salt = substr ($enteredPassword, 0, 2);
$userPswd = Crypt ($enteredPassword, $salt);
$USERPSWD is then stored in MySQL with the user name

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 $php_auth_user and $PHP_AUTH_PW, 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:

Application of Crypt () and Apache's password-response verification system

$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
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 the 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 is unauthorized to enter this area.";
Exit

else:

Print "This is the secret data!";

endif

?>

Above is a simple authentication system that verifies user access. 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.

I'll introduce another PHP-supported function, ━━MD5 (), which uses the MD5 hashing algorithm, which has several interesting uses worth mentioning:

Mixed
A mixed function can transform a variable-length information into an output with a fixed length that is mixed, also known as the "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
$msg = "This is some a message that I just wrote";
$enc _msg = MD5 ($MSG);
Print "Hash: $enc _msg";
?>

Results:

hash:81ea092649ca32b5ba375e81d8f4972c
Note that the length of the result is 32 characters. Take a look at the table below, where the value of $msg has a slight change:

Use MD5 () to mash a slightly changed string
Note that one of the missing s in the message
$msg = "This was some mesage that I just wrote";
$enc _msg = MD5 ($MSG);
Print "HASH2: $enc _msg

";
?>

Results:

hash2:e86cf511bd5490d46d5cd61738c82c0c
It can be found that although the length of the two results is 32 characters, a small change in the clear text makes a big difference in the results, so the mixed and MD5 () functions are a good tool for checking small changes in the 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.

Mcrypt
Mcrypt 2.5.7 Unix | Win32
Mcrypt 2.4.7 is a powerful cryptographic algorithm extension library that includes 22 algorithms, including the following:

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 instructions 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
Make install
CD to your PHP directory.
./configure-with-mcrypt=[dir] [--other-configuration-directives]
Make
Make install
Of course, depending on your requirements and the relationship between the PHP installation and the Internet Server software, the process above may need to be modified appropriately.

Using MCrypt
The advantage of MCrypt is not only that it provides more cryptographic algorithms, but also that it can add/decrypt data, and it 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
$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.

The two most typical functions in the above code are Mcrypt_encrypt () and Mcrypt_decrypt (), whose purpose 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, 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 package, and 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
Make install
Cd
./configure-with-mhash=[dir] [--other-configuration-directives]
Make
Make install
Like MCrypt, depending 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
It's easy to mash up the information and take a look at the following example:

$hash _alg = Mhash_tiger;
$message = "These is the directions to the secret fort. The steps left, the three steps right, and Cha Chacha. ";
$hashed _message = Mhash ($hash _alg, $message);
Print "The hashed message is". Bin2Hex ($hashed _message);
?>

Executing this section of the script will result in the following output:

The hashed message is 07a92a4db3a4177f19ec9034ae5400eb60d1a9fbb4ade461
The purpose of using the Bin2Hex () function here is to make it easier for us to understand the output of the $hashed_message because the result of the mixing is a binary format that you must convert to a hexadecimal format in order to be able to convert it into a format that is easy to understand.

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:

$hash _alg = Mhash_tiger;
Print "This data have been hashed with the". Mhash_get_hash_name ($hashed _message). hashing algorithm. ";
?>

The resulting output is:

This data have been hashed with the TIGER hashing algorithm.
One of the last things to note about PHP and encryption
The last important thing to note about PHP and encryption is that the data 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.

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