Home >Backend Development >PHP Tutorial >PHP data encryption_PHP tutorial

PHP data encryption_PHP tutorial

WBOY
WBOYOriginal
2016-07-15 13:22:54935browse

Data encryption has become more and more important in our lives, especially considering the large number of transactions that occur on the Internet and the large amount of data transmitted. If you are interested in adopting security measures, you will also be interested in learning about the series of security features provided by PHP. In this article, we will introduce these functions and provide some basic usage so that you can add security features to your application software.
Preliminary knowledge
Before introducing the security functions of PHP in detail, we need to take some time to introduce some basic knowledge about cryptography to readers who have not been exposed to this aspect. If you are already very familiar with the basic concepts of learning, you can skip this part.
Cryptozoology can be popularly described as the study and experiment of encryption/decryption. Encryption is the process of converting easy-to-understand data into difficult-to-understand data, and decryption is the process of converting difficult-to-understand data into original easy-to-understand data. process. Information that is difficult to understand is called a code, and information that is easy to understand is called a clear code.
Data encryption/decryption requires certain algorithms. These algorithms can be very simple, such as the famous Caesar code, but current encryption algorithms are relatively more complex, and some of them are even undecipherable using existing methods. .
PHP’s encryption function
Anyone who has a little experience using non-Windows platforms may also be quite familiar with crypt(). This function completes a function called one-way encryption. It can Encrypt some plaintext, but cannot convert the password into the original plaintext. Although this may seem like a useless feature on the surface, it is widely used to ensure the integrity of system passwords. Because once the one-way encrypted password falls into the hands of a third party, it cannot be restored to plain text, so it is of little use. When verifying the password entered by the user, the user's input also uses a one-way algorithm. If the input matches the stored encrypted password, the entered password must be correct.
PHP also provides the possibility to use its crypt() function to complete one-way encryption. I will briefly introduce the function here:
string crypt (string input_string [, string salt])
where the input_string parameter is the string that needs to be encrypted, and the second optional salt is a bit string , which can affect encrypted passwords, further ruling out the possibility of what are known as precomputation 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 discover the length of the interference string your system will use by executing 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 are the algorithms it supports and the length of the corresponding salt parameters:
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 $
User Authentication with crypt()
As an example of the crypt() function, consider a situation where you wish to create a PHP script The program restricts access to a directory to only users who can provide the correct username and password. I will store the data in a table in MySQL, my favorite database. Let's start our example by creating the 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 the table:
Username Password
clark keloD1C377lKE
bruce ba1T7vnz9AWgk
peter paLUvRWsRLZ4U
The plain codes corresponding to these encrypted passwords are kent, banner and parker respectively. Pay attention to the first two letters of each password. This is because I used the following code to create the interference 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 along with the username
I will use Apache's password-response authentication configuration Prompts the user for a username and password. A little-known fact about PHP is that it can recognize the username and password entered by the Apache password-response system as $PHP_AUTH_USER and $PHP_AUTH_PW. I will use this in the authentication script. two variables.Take some time to read the script below carefully and pay more attention to the explanations 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 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 is the secret data!" ;
endif;
?>
The above is a simple authentication system to verify user access rights. When using crypt() to protect important confidential information, remember that crypt() used by default is not the most secure and can only be used in systems with lower security requirements. If higher security is required Performance requires the algorithm I introduce later in this article.
Next I will introduce another function supported by PHP━━md5(). This function uses the MD5 hash algorithm. It has several interesting uses worth mentioning:
Mixing
A hashing function can transform a variable-length message into a fixed-length hashed output, also called a "message digest". This is useful because a fixed-length string can be used to check file integrity and verify digital signatures and user authentication. As it is suitable for PHP, PHP's built-in md5() hash function will convert a variable-length message into a 128-bit (32-character) message digest. An interesting feature of mixed encoding is that the original plain code cannot be obtained by analyzing the mixed information, because the mixed result has no dependence on the original plain code content. Even changing only one character in a string will cause the MD5 hybrid algorithm to calculate two completely different results. Let's first look at the contents of the following table and its corresponding results:

Use md5() to mix strings
$msg = "This is some message that I just wrote" ;
$enc_msg = md5($msg);
print "hash: $enc_msg ";
?>
Result:
hash: 81ea092649ca32b5ba375e81d8f4972c
Note that the length of the result is 32 characters. Take a look at the table below again, where the value of $msg has changed slightly:
Use md5() to mix a slightly changed string
//Note, There is one s missing in the message
$msg = "This is some mesage that I just wrote";
$enc_msg = md5($msg);
print "hash2: $enc_msg

";
?>
Result:
hash2: e86cf511bd5490d46d5cd61738c82c0c

It can be found that although the length of both results is 32 characters, a slight change in the plaintext makes the result happen. Large changes, therefore, hashing and the md5() function are a great tool for checking small changes in the data.
Although crypt() and md5() have their own uses, both are subject to certain limitations in functionality. In the following sections, we will introduce two very useful PHP extensions called Mcrypt and Mhash, which will greatly expand the encryption options 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 it in the form of the Mcrypt extension library this possibility.
Mcrypt
Mcrypt 2.5.7 Unix | Win32
Mcrypt 2.4.7 is a powerful encryption algorithm extension 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:
Mcrypt is not included in the standard PHP package, so you need to download it. The download address is:

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446934.htmlTechArticleData encryption has become more and more important in our lives, especially considering what happens on the Internet Large volumes of transactions and large amounts of data transferred. If you are interested in adopting security measures...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP FAQ_PHP TutorialNext article:PHP FAQ_PHP Tutorial