PHP Data Encryption

Source: Internet
Author: User
Tags format functions hash header mysql net php and variable
Encryption | The position of data encryption in our lives has become more and more important, especially considering the large amount of transactions and data transmissions that occur on the web. If you are interested in adopting security measures, you will also be interested in understanding the range of security features provided by PHP. In this article, we will describe these features and provide some basic usage so that you can add security features to your application.

Preliminary knowledge
Before introducing the security features of PHP in detail, we need to take a moment to introduce some basic knowledge about cryptography to readers who have not contacted the content, and skip this part if the basic concepts of cryptography are already well known.

Cryptography can be popularly described as the study and experiment of the addition/decryption, encryption is the conversion of understandable data to difficult to understand the process of information, decryption is to convert the information is not easy to understand the original process of information. The information that is not easy to understand is called the password, the understandable information is called the plaintext.

Data encryption/decryption need a certain algorithm, these algorithms can be very simple, such as the famous Caesar code, but the current encryption algorithm is relatively more complex, some of which use existing methods can not even decipher.

The encryption function of PHP
As long as a little experience with a non-Windows platform may be familiar to crypt (), this function is called one-way encryption, it can encrypt some plaintext, but can not convert the password to the original plaintext. Although this appears to be a useless feature on the surface, it is indeed widely used to ensure the integrity of the system's passwords. Because, once a one-way encrypted password falls into the hands of a third party, it is not useful because it cannot be restored to plaintext. When validating the password entered by the user, the user's input is also a one-way algorithm, if the input and stored encrypted password match, then the input message must be correct.

PHP also provides the possibility of using its crypt () function to complete a one-way encryption function. I'll briefly introduce the 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 encrypted cipher, further excluding the possibility of being called an estimated attack. By default, PHP uses a 2-character des jamming string, and if your system is using MD5 (which I will introduce MD5 algorithm later), it will use a 12-character jamming string. By the way, you can discover the length of the jamming string that the system will use by executing the following command:

Print "My system salt size is:". Crypt_salt_length;
The system may also support other cryptographic algorithms. Crypt () supports four algorithms, the following is the algorithm it supports and the length of 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 username and password to access the directory. I'll store the data in a table in MySQL, my favorite database. Let's start with our example by creating this table called 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. Notice the first two letters of each password, because I use the following code to create a jamming 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'll use Apache's password-answer authentication configuration to prompt the user for a username and password, a little-known information about PHP, which identifies the username and password entered by the Apache password-answer system as $php_auth_user and $PHP_AUTH_PW, I'll use these two variables in my authentication script. Take the 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 password-response verification system
<?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 ($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 (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 "are unauthorized to enter";
Exit

else:

Print "This is the secret data!";

endif

?>

Above is a simple authentication system that verifies the user's access rights. When using crypt () to protect important confidential information, keep in mind that the crypt () used in the default state is not the safest, only for systems with less security requirements, and if high security performance is required, I will need the algorithm that I have described later in this article.

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

Mixed
A mixed function can transform a variable-length information into an output with fixed-length mixed, also known as an "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 and user authentication. Because it is suitable for php,php built-in MD5 () hybrid functions will convert a variable-length information to 128-bit (32-character) Information Digest. An interesting feature of the hybrid is that it is not possible to get the original plaintext by analyzing the mixed information, because the result is not dependent on the original plaintext content. Even changing only one character in a string will make the MD5 hybrid algorithm compute two distinct results. Let's first look at the contents of the table and the corresponding results:

 
Using MD5 () to mix strings
<?php
$msg = "This is some the message I just wrote";
$enc _msg = MD5 ($MSG);
Print "Hash: $enc _msg";
?>

Results:

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

Use MD5 () to mix a slightly changed string
<?php
Note that an S is missing from the message
$msg = "This is some mesage I just wrote";
$enc _msg = MD5 ($MSG);
Print "HASH2: $enc _msg <br/><br/>";
?>

Results:

hash2:e86cf511bd5490d46d5cd61738c82c0c
As you can see, the mixed and MD5 () functions are a good tool for checking small changes in the data, although the two results are 32 characters long, but a small change in the plaintext changes the results significantly.

Although crypt () and MD5 () are useful, they are limited in function. In the following sections, we will introduce two very useful PHP extensions called MCrypt and Mhash, which will greatly expand the PHP user's choice of encryption.

Although we explained the importance of one-way encryption in the above section, sometimes we may need to encrypt the password data back to the original data, fortunately, PHP in the form of MCrypt Extension Library to provide this possibility.

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 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:
MCrypt is not included in the standard PHP package, so you need to download it and download the address: ftp://argeas.cs-net.gr/pub/unix/mcrypt/. After downloading, compile with 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] [--other-configuration-directives]
Make
Make install
Of course, depending on your requirements and the connection to your PHP installation with Internet Server Software, the process may need to be modified as appropriate.

Using MCrypt
The advantage of MCrypt is not only that it provides more encryption algorithms, but also that it can add/decrypt data, in addition, it also provides 35 kinds of functions for processing data. Although the details of these functions are beyond the scope of this article, I would like to briefly introduce a few typical functions.

First, I'll explain how to use the MCrypt extension library to encrypt data, and then explain how to use it to decrypt. The following code demonstrates this process by encrypting the data, displaying the encrypted data in the browser, and restoring the encrypted data to the original string, which is displayed on the browser.

Use MCrypt to add and decrypt data
<?php

Designate string to is 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 <p>";

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). " <p> ";
$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.

Encrypted string:02a7c58b1ebd22a9523468694b091e60411cc4dea8652bb8072 34fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b C89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 bfbab5e

Decrypted string:applied cryptography, by Bruce Schneier, is a wonderful cryptography.

The two most typical functions in the above code are Mcrypt_encrypt () and Mcrypt_decrypt (), and their use is obvious. I used the "Telegraph cipher This" mode, MCrypt provides several encryption methods, because each encryption method has the specific characters that can affect the security of the password, so each pattern needs to understand. The Mcrypt_create_iv () function may be more interesting to readers who have no access to a cryptographic system, although a thorough explanation of this function is beyond the scope of this article, but I still refer to the initialization vector it creates (hence, iv), This always allows 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 supplied in the required pattern.

Mhash Extension Library
http://sourceforge.net/projects/mhash/

The 0.8.3 version of the Mhash expansion Library supports 12 hybrid algorithms, carefully examining the Mhash v.0.8.3 header file Mhash.h can be aware that it supports the following hybrid algorithm:

CRC32 HAVAL160 MD5
crc32b HAVAL192 RIPEMD160
GOST HAVAL224 SHA1
HAVAL128 HAVAL256 TIGER
Installation
Like MCrypt, Mhash is not included in the PHP software package, and for non-Windows users, the following is the installation process:

Download the Mhash extension Library
Gunzipmhash-x.x.x.tar.gz
Tar-xvfmhash-x.x.x.tar
./configure
Make
Make install
CD <php directory >
./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, including the Mhash extension library, in http://www.php4win.de. Just download and unzip it, and then install it according to the instructions in the Readme.first document.

Using Mhash
Mixing the information is very simple, look at the following example:

<?php
$hash _alg = Mhash_tiger;
$message = "These are the directions 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);
?>

Executing this script will result in the following output:

The hashed message is 07a92a4db3a4177f19ec9034ae5400eb60d1a9fbb4ade461
The purpose of using the Bin2Hex () function here is to facilitate our understanding of the output of $hashed_message, because the result of the mixing is binary format, which must be converted to hexadecimal format in order to be able to convert it into an easy-to-understand format.

It should be noted that the integrated is a one-way function, the result is not dependent on input, so you can publicly display this information. This strategy is typically used to allow users to compare downloads and system administrator files to ensure the integrity of the file.

Mhash also has some other useful functions. For example, I need to output the name of an mhash-supported algorithm, because all of the algorithms supported by Mhash start with mhash_, so you can do this 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 is the data has 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 cannot prevent data from leaking during transmission. Therefore, if you want to achieve a complete security application, it is recommended to choose Apache-ssl or other security server layout.

Conclusion
This article describes one of PHP's most useful features, ━━ data encryption, which not only discusses the PHP built-in crypt () and MD5 () cryptographic functions, but also discusses powerful extensions for data encryption ━━mcrypt and Mhash. 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 it does not guarantee data security when data is transmitted by the client to the server side.

Related Article

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.