The encryption function in PHP

Source: Internet
Author: User
Tags crypt header md5 mysql php script query variable access
Encrypting data encryption has become more and more important in our lives, 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 $1$
Crypt_blowfish 16-character beginning with $2$

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 = "hellodolly";
$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:



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.