Encrypt a PHP program to protect data from ordinary people

Source: Internet
Author: User
Tags gpg gpg encryption html tags php file php code php form php script sql injection

In this increasingly virtual world of the Internet, you have to be careful to protect your own data. This article describes the basics of encoding and encrypting some important information, such as passwords, credit card numbers, or even the entire message. And by using PHP's built-in features, understand the meaning of encrypting and decrypting information, and will learn some practical examples involving passwords and other data.
Understand the difference between today's real world and the real world 20 years ago. In the the 1980s, cryptography was an act of a secret agent-a plot you could read in Tom Clancy's detective story. If someone wants to keep a small amount of private information, he must encrypt the data using a password, pass phrase, or other basic method.

And now, encryption is all over the world. Passwords are also encrypted and stored in the database. Encrypted channels in cyberspace may be encrypted via 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 e-mails.

As a PHP developer, you should know that strong security practices do not only use security for unique applications-they can also be used for projects you are currently working on. Users should establish awareness of the transition to various advanced encryption methods (such as DES, MD5, SHA1, and Blowfish) from the general encryption method, such as not displaying plaintext in the password field on the login page.

There is no way to discuss all aspects of encryption due to time and space, but you will learn from here the basics that cover most situations that apply to you. By using PHP's built-in features, we first understand the meaning of encrypting and decrypting information, and then learn some practical examples involving passwords and other data. In this article, encryption is discussed in a larger security context. Finally, other PHP extensions and Plug-ins will be introduced.

A Primer on encryption technology

As a Greek root asset, cryptography is an art of "mystical writing". Caesar's password is one of the oldest passwords, and the simplest form. It uses the clear text message, moves the letter n position, thus produces the dark text. For example:

PlainText: Veni Vidi Vici
Dark Wen: xgpk xkfk Xkek
By examining the dark text and using some heuristic techniques, you can tell that the plaintext is actually moving two characters. Caesar's code is easy to crack. For example: Check the above information and know that X repeats several times, and so does K. This becomes a guessing puzzle, determining how many four-letter words have so many vowels. Once you know these words with vowels, you know how to move the rest of the words. It also helps you to determine whether the plaintext is Latin and gives you a general idea of it.

Modern cryptography is very powerful, using algorithms that transcend the unified movement of letters and symbols. This article is not going to cover these algorithms in detail, just a few PHP installations, including everything you need to keep your data secure (or especially).

There are no 100% absolutely complete encryption methods that are not subject to attack. Roughly every one months, some hackers and their friends will assemble 1,000 computers, and in the first few days, brute force computational damage, thus breaking the latest encryption method. However, you can seal your system and data to keep hackers from interfering and trespassing. They will look for an opportunity elsewhere.

With that in context, let's turn to the sample PHP applications that are protected by simple login.

No security or encrypted PHP form handling

Assuming you are a new WEB application developer, there is no more opportunity to use security features. You created your first application, which stores user names and passwords in the private user table, but you did not encrypt these passwords. These passwords exist in the form of a glance that anyone can use to access the database. You can build a login page that looks like this.

Listing 1. Simple login Page

username


password




What is wrong with this HTML tag? The input type selected for the password field is text, which means that any content that the user types into the field is displayed on the screen in clear text.

You can easily change the type to password and replace the user input in the field with a string of asterisks. Is it reliable? Absolutely reliable. However, this step is ignored in many applications. Small as it is, it can make people feel uneasy about security. Are you willing to deposit the money in the window of the rest hall and be badly damaged by the bank? Maybe you will. But you might even expect the bank to be intact. The same is true for applications.

Let's continue with the verify.php file that processes the form submission.

Listing 2. Simple PHP Login Verification

$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
}

? >

Read this, you will show a satisfactory smile. Some readers who are waiting to read the encryption section of this article may become impatient, but encryption is only part of the security issue. You must also intelligently handle the introduced user data. The DeveloperWorks tutorial "Locking Your PHP application" (see Resources) discusses SQL injection: Sending unhealthy data to the database can lead to harmful or unfounded access. No matter how many encryption you use, exposing vulnerabilities is no good.

You should follow the traditional security guidelines: "Do not trust user-supplied data" and "defense-in-depth", purge incoming data, and protect the database by escaping incoming strings (see Listing 3). Defense-in-depth is the safekeeping of redundant security methods-not only encryption, but also intelligent processing of the data provided by the user.
Listing 3. Protection of PHP form resolution from user data manipulation

$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 rationalizing the use of Strip_tags (), substr (), and mysql_real_escape_string (), you can remove any potentially unwanted commands, 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 way to fix this is to use PHP's built-in crypt () feature.

Using crypt ()

PHP's built-in crypt () feature enables one-way encryption or one-way hashing. It is only one-way, because after you encrypt something, you can never turn it back to plaintext. At first glance, the idea seems absurd. Using encryption primarily protects the information and can then be used, which usually means that it can be decrypted.

Don't despair. One-way encryption schemes and crypt () are particularly popular. You can make the method of protecting information more secure. If your user password list falls into the wrong hands, they actually do not have the means to decrypt the password as plaintext.

Let's go back to the password example. Note (notational) PHP applications may include modules that allow system administrators to create, edit, and delete users. For example, a PHP script can encrypt a password using crypt () before storing the user record in the user table.

Listing 4. Encrypt passwords using crypt ()

$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 () takes a string of plaintext as its first parameter word, and applying salt to it affects the randomness of the cryptographic algorithm and generates a one-way dark text for the input plaintext. If you do not provide a salt, 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, beginning with $1$
Crypt_blowfish 16 characters, beginning with $2$


Many modern PHP installations use MD5 or higher salt, which uses a powerful 12-character salt, but don't take anything for granted. You'd better know which value the system is using. You can check the server's settings using the following PHP code fragment:

The answer returned will be 2, 9, 12, or 16, which tells you the value that the system is using. To use the MD5 or later version of the salt, you can explicitly invoke the crypt () function and the MD5 () function in the plaintext and salt parameters to obtain a random ciphertext (see listing 5). The MD5 () function can hash any string of feedback and convert it to a fixed length of 32 characters string. You may prefer other methods, depending on security requirements and personal interests.

Listing 5. Encrypt passwords using crypt () and MD5 ()

$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..
? >

There is already an encrypted password in the database, but there is no way to decrypt it. How to make it useful? An easy way to do this is to use the same encryption method for any incoming password that the user provides, and compare the results to the password that you store.

Listing 6. Re-visit verify.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 encrypted password stored is I83UW28JKZBRZF, the encrypted store the incoming password and compares it to the stored password. The only way an attacker destroys encryption is to compare a very long list of strings with your encrypted password, each time comparing one until a match is found. This is also known as a dictionary attack, so your password should ideally not be a password or a Star Trek character name, or even your claim. Because after encrypting Fido, it becomes a mess, but that doesn't mean it's safe for this attack. Make sure that your password has a certain length (eight or more characters) and contains uppercase letters, numbers, and specific characters, such as! and $, so it would be more difficult to guess your data. In the phrase, f1d0! is a better password than a long cipher such as Gandalfthegray, which uses lowercase letters and is the "Lord of the Rings" character name.

A less-than-good way to use crypt ()

There is another way to use Crypt (), which is not very good: Use the first n characters of the plaintext as a salt.

Listing 7. Use a text character for salt

$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 to TM, which makes it easy for someone to infer the contents of the salt. This is not a good way.

Using PHP for encryption and decryption

The bulk of this article discusses one-way encryption using crypt (). But what if you want to send a message to someone and provide a way to decrypt the message? Please use the public key cryptography supported by PHP.

Users who use public key cryptography 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 encrypt the message using John Doe's public key, which you have stored in your own keyring. When John Doe receives the message, only he can decrypt it using his private key. The public and private keys of any given user are mathematically irrelevant. For PGP and other public-key cryptography methods, there is no way to infer someone's private key from the public key.

The additional feature of PGP is that the password for the private key is not actually a password, it is a passphrase. It can be an entire sentence, including punctuation, spaces, and all character styles.

One way to use public key cryptography based on PGP is to use the GNU privacy Guard (GPG). Any message that uses GPG encryption can be decrypted using GPG, PGP, or any number of e-mail client plug-ins that support any program. In the example, the online table accepts user input (including messages), encrypts the message for a specific receiver using GPG, and then sends a message.
Listing 8. Using GPG

Set up users
$from = "webforms@example.com";
$to = "you@example.com";

Cut of the message down to size, remove HTML tags
$messagebody = Strip_tags (substr ($_post[' msg '],0,5000));
$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 invokes/USR/LOCAL/BIN/GPG (this location varies by server) to encrypt the message using the sender's private key and the receiver's public key. As a result, only the receiving party can decrypt the message and know the message from the sender. In addition, you can set the home and USER environment variables to inform GPG where to find the keyring that stores these keys. The functions of other flags are as follows:

--quiet and--no-secmem-warning suppress warnings from GPG.
--encrypt performs encryption.
--sign to verify the identity of the sender by adding a signature.
--armor produces a non binary ASCII output, which makes it easy to send it by e-mail.
Normally, as mentioned earlier, the cryptographic keys are protected by passphrase. This particular instance does not use a passphrase because it needs to be entered manually every time the form is submitted. Of course, you can also select other options when you provide a phrase in a separate file, or use its own authentication scheme to prevent form public (for example, if it is a form that can only be accessed by a company sales representative).

Also note that unless you are using SSL for a table that allows users to enter e-mail messages, anything you type is in clear text. In other words, anyone between the client and the server can see it. However, this is another topic.

Conclusion

We've introduced a lot of security, encryption, and even public-key cryptography to help you successfully develop the next PHP project. The key to using encryption and other encryption methods is not to create 100% of reliable seamless systems. A computer that is shut down is a system that is not to be attacked, but it is not completely guaranteed, because someone may walk up to it, open it, and then attack it. The point of encryption is to make it very difficult to get sensitive data so that hackers no longer attempt to attack, or try to leave after the attack fails.

All security considerations must be balanced with convenience and protection. Using a powerful algorithm key to encrypt all data in one way means that your data is safe, but inconvenient to use. The corresponding flaws are also very serious, as with unencrypted content, any convenience for you is also a terrible convenience for other people to get the data. The best balance can be achieved by encrypting important confidential data, such as passwords, credit card numbers, and secret messages, and by adding good security measures such as defense-in-depth, filtering user-supplied data, and traditional general knowledge.



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.