PHP Data Encryption _php Tutorial

Source: Internet
Author: User
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 you need to download it and download the address:

http://www.bkjia.com/PHPjc/446934.html www.bkjia.com true http://www.bkjia.com/PHPjc/446934.html techarticle 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 ...

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