Encrypt data to ordinary people and use PHP programs to protect data

Source: Internet
Author: User
Tags crypt
To protect data with PHP programs and to protect data with PHP programs, you must be careful to protect your data in an increasingly virtualized internet world. This article describes how to encode and encrypt important information (such as passwords, credit card numbers, and even the entire message. And learn about encryption and "> <LINKhref =" http: // www. php100.

In this increasingly virtualized Internet world, you must be careful to protect your data. This article describes how to encode and encrypt important information (such as passwords, credit card numbers, and even the entire message. You can use the built-in functions of PHP to understand the meaning of encryption and decryption, and learn some practical examples involving passwords and other data.
Understand the differences between today's real world and the real world 20 years ago. In 1980s, encryption was an activity of special agents-a plot that you only read in Tom Clancy's detective novels. If a person wants to keep a small amount of private information, he must encrypt the data using a password, phrase, or other basic methods.

Encryption is now available in various fields. The password is encrypted and stored in the database. Encrypted channels in computer space may be encrypted through SSL, SSH, and other technologies-not to mention virtual private networks. People can and must be able to use Pretty Good Privacy (PGP) to protect sensitive files and emails.

As a PHP developer, you should know that strong security practices do not just apply security protection to unique applications-they can also be used for your current project. The user needs to establish a transition from a general encryption method (for example, the password field on the login page does not display plain text) to a variety of advanced encryption methods (such as DES, MD5, SHA1 and Blowfish) awareness.

Due to the limited time and space, we cannot discuss all aspects of encryption here, but you will learn about the basic content that applies to most of your situations. By using the PHP built-in function, we can first understand the meaning of encryption and decryption of information, and then learn some practical examples involving passwords and other data. In this article, encryption is discussed in a larger security context. Finally, we will introduce other PHP extensions and plug-ins.

Basic reading of encryption technology

As the root asset of Greece, encryption technology is a "mysterious writing" art. The Caesar password is the oldest and simplest form. It uses plaintext messages to move letters n locations to generate a dark text. For example:

Plaintext: Veni Vidi Vici
Dark text: Xgpk Xkfk Xkek
By checking the dark text and using some heuristic techniques, you can know that the plain text actually moves two characters. The Caesar password is easy to crack. For example, if you check the preceding information, we can see that X is repeated multiple times, and k is the same. This turns into a guess, and determines how many 4-letter words have that many vowels. After knowing these words with vowels, you will know how to move the remaining words. It can also help you determine whether the plain text is in Latin and give you a general understanding of it.

The modern encryption technology is very powerful and uses an algorithm that surpasses unified mobile letters and symbols. This article does not describe these algorithms in detail. it only describes some PHP installations, including all the content that you need to moderate (or especially) maintain data security.

There is no absolutely complete encryption method of 100% not under attack. Around every other month, some hackers and their friends will gather 1,000 computers and perform powerful computing damages in the first few days, resulting in the crash of the latest encryption method. However, you can seal your system and data to prevent hacker interference and illegal intrusion. They will look for opportunities elsewhere.

After learning about this, let's turn to the example PHP applications protected by simple login forms.

PHP processing without security protection or encryption

Assume that you are a new Web application developer and have no chance to use security features. You have created your first application, which can store user names and passwords in the dedicated user table, but you have not encrypted these passwords. These passwords exist at a glance and can be used by anyone to access the database. You can build a logon page as shown below.

List 1. simple logon page

<Form action = "verify. php" method = "post">
<P> <label for = 'username'> username </label>
<Input type = 'text' name = 'username' id = 'username'/>
</P>
<P> <label for = 'password'> password </label>
<Input type = 'text' name = 'password' id = 'password'/>
</P>
<P> <input type = "submit" name = "submit" value = "log in"/>
</P>
</Form>

What is the problem with this HTML tag? The input type selected for the password field is text, which means that any content you type in this field will be displayed in plaintext on the screen.

You can easily change this type to password and replace user input in this field with a string of asterisks. Is it reliable? Absolutely reliable. However, this step is ignored in many applications. Although things are small, security can make people feel uneasy. Are you willing to deposit the money into the bank that has been badly damaged in the window of the rest hall? Maybe you will. However, you may expect the bank to be intact. The same applies to applications.

Let's continue with the verify. php file for processing form submissions.

Listing 2. simple PHP login verification

<? Php
$ User = $ _ POST ['user'];
$ Pw = $ _ POST ['password'];

$ SQL = "select user, password from users
Where user = '$ user'
And password = '$ pw'
Limit 1 ';
$ Result = mysql_query ($ SQL );

If (mysql_num_rows ($ result )){
// We have a match!
} Else {
// No match
}

?>

After reading this, you will be satisfied with your smile. Some readers who are waiting to read the encryption part of this article may become impatient, but encryption is only part of the security issue. You must also intelligently process imported user data. The developerWorks tutorial "locking your PHP application" (see references) discusses SQL injection: sending abnormal data to the database can lead to harmful or unfounded access. No matter how much encryption you use, making public vulnerabilities is no good.

You should follow the following traditional security principles: "Do not trust the data provided by users" and "deep defense"; clear incoming data and protect the database by escaping the input string (see listing 3 ). Deep defense is to keep redundant security methods safe-not only encryption, but also intelligent processing of data provided by users.
Listing 3. protecting PHP parsing from user data operations

<? Php
$ User = strip_tags (substr ($ _ POST ['user'], 0, 32 ));
$ Pw = strip_tags (substr ($ _ POST ['password'], 0, 32 ));

$ SQL = "select user, password from users
Where user = '". mysql_real_escape_string ($ user )."'
And password = '". mysql_real_escape_string ($ pw )."'
Limit 1 ';
$ Result = mysql_query ($ SQL );

If (mysql_num_rows ($ result )){
// We have a match!
} Else {
// No match
}
?>


By reasonably using strip_tags (), substr (), and mysql_real_escape_string (), you can delete any potentially harmful command, reduce the string to 32 characters, and remove all special characters, the database may interpret these characters as part of an unexpected command string.

At the end of this process, there is still a plaintext password in the database. You cannot display it. The easiest solution is to use the built-in crypt () function of PHP.

Use crypt ()

PHP's built-in crypt () function enables one-way encryption or one-way hashing. It is only one-way, because after you encrypt a content, you can never reverse it to plain text. At first glance, this idea seems ridiculous. Encryption is used to protect information, which can then be used. The latter usually means that it can be decrypted.

Don't despair. One-way encryption and crypt () are particularly popular. This makes information protection methods more secure. If your user password list falls into the hand of an unhandled hacker, they do not actually have a way to decrypt the password into plain text.

Let's return to the password example. Notational PHP applications may include modules for system administrators to create, edit, and delete users. For example, before storing user records in a user table, the PHP script can use crypt () to encrypt the password.

Listing 4. use crypt () to encrypt the password

<? Php
$ User = strip_tags (substr ($ _ POST ['user'], 0, 32 ));
$ Pw = strip_tags (substr ($ _ POST ['password'], 0, 32 ));

$ Cleanpw = crypt ($ pw );

$ SQL = "insert into users (username, password)
Values ('". mysql_real_escape_string ($ user )."',
'". Mysql_real_escape_string ($ cleanpw )."')";
// ...... Etc ....
?>

Crypt () uses a string of plain text as its first parameter. applying salt to it will affect the randomness of the encryption algorithm and generate one-way dark text of the input plain text. If salt is not provided, PHP usually defaults to its system salt, which can be one of the following values and lengths:
Algorithm Salt
CRYPT_STD_DES 2 characters (default)
CRYPT_EXT_DES 9 characters
CRYPT_MD5 12 characters, starting with $1 $
CRYPT_BLOWFISH 16 characters, starting with $2 $


Many modern PHP installations use MD5 or higher salts, which use a powerful 12-character salt, but do not take anything for granted. You 'd better know which value the system is using. You can use the following PHP code snippet to check the server settings:

<? Php echo "System salt size:". CRYPT_SALT_LENGTH;?>

The returned answer is 2, 9, 12, or 16, which tells you the value being used by the system. To use an MD5 or higher version of salt, you can explicitly call the crypt () function and the md5 () function in the plaintext and salt parameters to obtain a random dark text (see listing 5 ). The md5 () function can hash any feedback string and convert it to a string of a fixed length of 32 characters. You may prefer other methods. the specific usage depends on your security needs and interests.

Listing 5. use crypt () and md5 () to encrypt passwords

<? Php
$ User = strip_tags (substr ($ _ POST ['user'], 0, 32 ));
$ Pw = strip_tags (substr ($ _ POST ['password'], 0, 32 ));

$ Cleanpw = crypt (md5 ($ pw), md5 ($ user ));

$ SQL = "insert into users (username, password)
Values ('". mysql_real_escape_string ($ user )."',
'". Mysql_real_escape_string ($ cleanpw )."')";
// ...... Etc ....
?>

The database now has an encrypted password, but there is no decryption method for it. How to make it useful? One easy way is to use the same encryption method for any input password provided by the user, and compare the result with the password you stored.

Listing 6. revisit verify. php

<? Php
$ User = strip_tags (substr ($ _ POST ['user'], 0, 32 ));
$ Pw = strip_tags (substr ($ _ POST ['password'], 0, 32 ));
$ Cleanpw = crypt (md5 ($ pw), md5 ($ user ));

$ SQL = "select user, password from users
Where user = '". mysql_real_escape_string ($ user )."'
And password = '". mysql_real_escape_string ($ cleanpw )."'
Limit 1 ';
$ Result = mysql_query ($ SQL );

If (mysql_num_rows ($ result )){
// We have a match!
} Else {
// No match
}
?>
For example, if the stored encryption password is i83Uw28jKzBrZF, encrypt the input password and compare it with the stored password. The only way for attackers to destroy encryption is to compare a very long string list with your encrypted password. each time you compare one string until a matching item is found. This is also called a dictionary attack. Therefore, your password should not be a password or a Star Trek character name, or even your name. After Fido is encrypted, it becomes a pile of gibberish, but this does not indicate that it is safe for such attacks. Make sure that your password has a certain length (eight or more characters) and contains uppercase letters, numbers, and specific characters, such! And $, which makes it more difficult to guess your data. In the phrase, f1D0! It is a better password than a long password like GandalftheGray, because the latter uses lowercase letters and is a character name of "Lord of the Rings.

A bad way to use crypt ()

Another way to use crypt () is to use the first n characters in plain text as salt.

Listing 7. use plain text characters in salt

<? Php
$ User = strip_tags (substr ($ _ POST ['user'], 0, 32 ));
$ Pw = strip_tags (substr ($ _ POST ['password'], 0, 32 ));
$ Cleanpw = crypt ($ pw, substr ($ user, 0, 2 ));

$ SQL = "select user, password from users
Where user = '". mysql_real_escape_string ($ user )."'
And password = '". mysql_real_escape_string ($ cleanpw )."'
Limit 1 ';
$ Result = mysql_query ($ SQL );

If (mysql_num_rows ($ result )){
// We have a match!
} Else {
// No match
}
?>

If your username is tmyer, the salt is preset as tm, which makes it easy for someone to deduce the content of the salt. This is not a good method.

Use PHP for encryption and decryption

In most sections of this article, we will discuss how to use crypt () for one-way encryption. However, if you want to send a message to someone and provide a method to decrypt the message, what should you do? Use the public key encryption technology supported by PHP.

Users who use public key encryption have a private key and a public key, and they share the public key with other users. If you want to send a private text message to your friend John Doe, you can use the John Doe public key (which you have stored in your own keyring) to encrypt the message. After John Doe receives the message, only John Doe can use his private key to decrypt it. The public key and private key of any given user cannot be related in mathematics. For PGP and other public key encryption methods, there is no way to deduce a person's private key from the public key.

The additional features of PGP are: the private key password is actually not a password, it is a passphrase. It can be an integral sentence, including punctuation marks, spaces, and all character styles.

One way to use PGP-based public key encryption is to use GNU Privacy Guard (GPG ). Any message encrypted with GPG can be decrypted using GPG, PGP, or any number of email client plug-ins that support any program. In the example, the online table accepts user input (including messages), uses GPG to encrypt messages for specific receivers, and then sends messages.
Listing 8. using GPG

<? Php
// Set up users
$ From = "webforms@example.com ";
$ To = "you@example.com ";

// Cut the message down to size, remove HTML tags
$ Messagebody = strip_tags (substr ($ _ POST ['MSG ));
$ Message_body = escapeshellarg ($ messagebody );

$ Gpg_path = '/usr/local/bin/gpg ';
$ Home_dir = '/htdocs/www ';
$ User_env = 'web ';

$ Cmd = "echo $ message_body HOME = $ home_dir USER = $ user_env $ gpg_path ".
"-- Quiet -- no-secmem-warning -- encrypt -- sign -- armor ".
"-- Recipient $ to -- local-user $ from ";

$ Message_body = '$ cmd ';

Mail ($ to, 'Message from Web form', $ message_body, "From: $ from \ r \ n ");

?>

In this example, PHP calls/usr/local/bin/gpg (this location varies with the server) to encrypt messages using the private key of the sender and the public key of the receiver. As a result, only the receiver can decrypt the message and know the message from the sender. In addition, you can set the HOME and USER environment variables to notify the GPG where to find the keyring that stores these keys. Other features are as follows:

-- Quiet and -- no-secmem-warning suppress warnings from GPG.
-- Encrypt performs encryption.
-- Sign: add a signature to verify the sender's identity.
-- Armor generates non-binary ASCII output, which is easy to send by email.
Normally, as mentioned above, secret keys are protected by cryptographic phrases. The password phrase is not used for this specific instance, because it needs to be manually entered every time a form is submitted. Of course, you can also select other options in the following situations: provide a phrase in a separate file, or use its own authentication scheme to prevent forms from being public (for example, if it is a form that can only be accessed by the company sales representative ).

Note that unless you are using SSL for a table that allows users to enter email messages, all the entered content is in plain text. In other words, anyone between the client and the server can see it. However, this is another topic.

Conclusion

We have introduced a lot about security, encryption technology, and even public key encryption technology to help you successfully develop the next PHP project. The key to using encryption and other encryption methods is not to create a 100% reliable, seamless system. A disabled computer is not an attack system, but it cannot be completely guaranteed because someone may go forward, open it, and then attack it. The key aspect of encryption is to make it very difficult to obtain sensitive data, so that hackers no longer attempt to attack, or leave after an attempt to attack fails.

Convenience and protection must be taken into account for all security considerations. Using a powerful algorithm key to encrypt all data in one way means that your data is safe but inconvenient to use. The corresponding defects are also very serious. just like using non-encrypted content, any convenience you bring brings to other people's access to data is terrible. By encrypting important confidential data (such as passwords, credit card numbers, and secret messages) and adding security measures (such as deep defense, filtering user data and traditional general knowledge) the optimal balance can be achieved.

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.