8 Encryption

This chapter covers the need for encryption, its importance in data security, and what can happen if it fails or if encryption of vital data isn’t implemented. We will revisit the code from Chapter 7, “Authentication,” and show you how to better secure the application.

What Is Encryption?

Encryption is the process of transforming information into something that is unreadable to anyone not possessing special knowledge. This transformation requires two crucial pieces of data: the cipher and the key. In the world of programming, the cipher is an algorithm. The special knowledge you must have to read the encrypted data is called the key. There are several ciphers, or encryption algorithms, that are available for you to use in your own application.

There are two major types of encryption: symmetric key and asymmetric or public key. Each type has multiple variations, each with its own strengths and weaknesses. We will try to help you understand when to use either type. As of PHP 6.0, PHP supports symmetric and asymmetric key encryption natively.

In a public key encryption scheme, there are two keys. One is kept private by the receiver; this is used to decrypt the message. The other key is supplied by the receiver to the sender; this is the public key and is used to encrypt the message. Only someone with the matching private key can then decrypt what is sent. The sender and the receiver have different keys. That is what makes this form of encryption asymmetric. This method is very good when you have lots of senders, such as with e-mail or for digital signatures and SSL. These methods of encryption are not natively implemented in PHP until PHP 6.0, but you can add extensions to add SSL or call some public key ciphers as external functions. Figure 8.1 shows how public key encryption works.

Figure 8.1. Diagram of asymmetric encryption.

Diagram of asymmetric encryption.

In symmetric key encryption both the sender and the receiver share a key. This key is then used by the algorithm to encrypt or decrypt the information. The major drawback of this method is key management. Everyone who needs to decrypt the message must have the key, and all must remember which key is for which message. This method is very useful for encrypting data that another application will read or in situations where the sender and receiver are static. If you are in a situation where there will be multiple users of the key, this method is not ideal. Figure 8.2 shows how symmetric encryption works.

Figure 8.2. Diagram of symmetric encryption.

Diagram of symmetric encryption.

There is also a useful variant of symmetric encryption called one-way encryption, where you encrypt the message with no intention of ever decrypting it. Figure 8.3 shows this type of one-way encryption.

Figure 8.3. Diagram of one-way encryption.

Diagram of one-way encryption.

One-way encryption can be used in password situations where two pieces of information match when encrypted. We will look at one form of symmetric encryption that involves using large hash tables. This is very useful for data integrity checking because any minor change in an object will cause a large change in the resulting hash.

Choosing an Encryption Type

When you are trying to decide how to secure your data, there are a few main points to consider:

• Algorithm strength

• Application speed versus data security

• Use of the encrypted data

In the following sections, we’ll look at each in a bit of detail.

Algorithm Strength

There are many algorithms to choose from. The PHP built-in mcrypt() function has over 20 different encryption options, and there are third-party libraries that add even more. This can be rather bewildering, so it’s important to remember that key length and predictability of the algorithm determine its strength. That simply means the longer the key (the more bits it uses), the longer it will take someone to break it. But there is a stipulation. If the algorithm is predictable, the number of guesses needed to break the encryption can be greatly reduced. No one expects you to keep up with all of the cryptology news as to which method is easier to crack. Unless you’re one of those people who does calculus for fun, you probably have more interesting things to do. As long as you stick with the newest algorithms, you should be OK. Currently, 3DES, AES, and Blowfish are our recommendations.

For hashing, the PHP implementations of MD5 and SHA1 will work, but be aware that MD5 can be compromised. If you need a strong hash you may need to look at a third-party implementation.

On occasion, especially in older easy security guides, XOR or ROTX will be mentioned. These are bit manipulations that can make the data look encrypted, but they are very basic and easily guessed. If you are trying to secure your data, do not use these. They are both examples of data obfuscation as opposed to true encryption.

Speed versus Security

The question to ask yourself concerning this issue is “How secure does my data need to be?” The bigger the key, the longer it will take to encrypt and decrypt the data. This can cause a noticeable slowdown in the time it takes your application to load and process data. If you are looking at data that needs to be very secure, you may want to use multiple methods of encryption.

A big part of addressing this issue comes down to what data is being encrypted and why. Do you just want to keep the casual user from viewing the text, or are you trying to secure the information from determined attackers? If it’s a question of casual observation, you may be able to get away with obfuscation instead of encryption. Another aspect of this is simply the likelihood of viewers. If it’s a closed system, data security may be handled by physical security. For example, if the data is being stored on a server with no connection whatsoever with the outside world, it may be enough to simply lock the server room and monitor who has physical access to the server. You may not even need encryption in this scenario.

Use of the Data

Ask yourself this question: “How is the data going to be used?” Something like a password that needs to be secret and verified works well with hashing. Are you looking to send or receive the information from a third party? If so, asymmetric encryption may be the way to go. If your application will be encrypting and decrypting the information, then symmetric encryption would be best.

Password Security

In Chapter 7, “Authentication,” we discussed the importance of choosing a strong password. Although this is important, it is not the only thing that needs to be done to secure your users’ logins. If either your database or flat file is compromised, plain-text passwords will be exposed to the attacker. To truly secure passwords we need to encrypt them.

Let’s look again at our three criteria for choosing an encryption type, but this time in the context of our example application. This is a publicly accessible system so we need a strong algorithm, but it is just a guestbook so we don’t need to go nuts. Nothing like a credit card or Social Security number is getting stored. The consequences of a data breach are fairly minor—a user could get locked out of his or her account, or someone could post a comment to the guestbook under another user’s name. All told, the worst-case scenario really isn’t a crisis situation, just a hassle.

We need the algorithm to work very quickly, as this is a Web application. No one is willing to wait to get to our page. The data is going to be a password, not something we will ever need to decrypt. If the user forgets his or her password, we will just initiate the process of creating a new one.

Knowing these things, we will choose the MD5 hash to encrypt our passwords. MD5 can be compromised, but that still takes a significant amount of time. MD5 is quick, easy to implement, and secure enough for our purposes. If your situation calls for more security, SHA1 will work as well, or implement SHA2 with a third-party library. No matter what you implement, if you need a strongly secured password, you need to have a password retention policy. A six-month or shorter mandatory password life will greatly reduce the chances that someone can brute-force the password.

Patching the Application to Encrypt Passwords

Adding encryption to user authentication in the guestbook application will happen in three steps:

1. Modify the user table in the database.

2. Create the encryption and salting functions.

3. Modify the password validation.

Breaking the task into discrete steps helps ensure that we can consider each part of the problem carefully and avoid introducing security holes into our application. The salting function is used to introduce an element of randomness into the encryption. Without it, anyone who knows the username and password could generate the same encrypted string as our encryption function. Adding salt to the algorithm is an easy way to make the system more secure.

Modifying the User Table

We need to add a column to the user table. The new column will hold a random number used to encrypt the password. Table 8.1 outlines the characteristics of this new field.

Table 8.1. Characteristics of the Random Number Field

image

Once we’re finished with the database, we’ll tackle the application code.

Create the Encryption and Salting Functions

Next, we’ll create a very simple function that encrypts the password. We’re making the assumption that the password has already been through data validation by the time it gets to the encryption function, so we’re not going to worry about that. This function is very simple, yet powerful enough for our purposes. First, we concatenate the username, salt, and password into a simple plain-text string. Then we pass that string through the built-in md5() function and return the results. It’s really that simple.

      function encryptPassword($plaintext_password, $username, $salt) {
            // At this point we can assume that the plaintext_password has already
            // been through validation, so there's no need to worry about tainting
            $str = $username.$salt.$password;
            return md5($str);
      }

To generate the salt for our encryption algorithm, we simply return a random number between 0 and 1,028.

      function createSalt() {
            return rand(1028);
      }

Modify the Password Validation System

The final step in encrypting the passwords in our guestbook application is to make a few minor modifications to the existing password and login system. First, we rewrote the password function to pass the plain-text password through our new encryptPassword() function.

function password($plaintext_password = NULL) {
            if($plaintext_password) {
                  $this->_password = encryptPassword($this->_username, $this->_salt,
                  $plaintext_password);
            }
            return $this->_password;
      }

Then we used the createSalt() and encryptPassword() functions in our login function as well.

function login($username, $plaintext_password) {
            $dbh = getDatabaseHandle();
            $selected_db = mysql_select_db("guestbook", $dbh);
            $sql = "select username, password from Users where username =
            $username";
            $result = mysql_query($sql, $dbh);
            $userinfo = mysql_fetch_array($dbh);
            $salt = createSalt();
            $password = encryptPassword($userinfo['password'], $salt,
            $plaintext_password);
            if($userinfo['password'] == $password) { // User is authenticated
                  $user = new User($username);
                  $user->_sessionID = _generateSessionID(); // Also stores
                  // sessionID in DB
                  return $user;
            } else {
                  return FALSE;
            }
      }

Wrapping It Up

In this chapter, we covered the need for encryption. We discussed how to decide on the right type of encryption for your application by understanding your data, and we covered a very common encryption scenario. This is a good start and should be enough to get you up and running with your own applications, but it is just a quick overview. Encryption and cryptography are huge topics that would require their own book to cover in depth. If you plan to store sensitive data, such as credit card numbers or Social Security numbers, we highly recommend that you familiarize yourself with encryption more thoroughly by reading one (or more) of the books listed in the Appendix, “Additional Resources.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225