Using MCrypt
Frequently Web applications will encrypt and decrypt data stored in a database, using the database-supplied functions. This is appropriate, as you want the database to do the bulk of the work whenever possible. But what if you want to encrypt and decrypt data that's not being stored in a database? In that situation, MCrypt is the best solution. To use MCrypt with PHP, you'll need to install the MCrypt library (libmcrypt, available from http://mcrypt.sourceforge.net) and configure PHP to support it (Figure 4.16)
Figure 4.16 Run a phpinfo() script to confirm your server's support for MCrypt.
For this example, I'll show you how to encrypt data stored in a cookie, making it that much more secure. Because the encryption process creates binary data, the base64_encode() function will be applied to the encrypted data prior to storing it in a cookie. Therefore, the base64_decode() function needs to be used prior to decoding the data. Other than that little tidbit, the focus in the next two scripts is entirely on MCrypt.
Do keep in mind that in the next several pages I'll be introducing and teaching concepts to which people have dedicated entire careers. The information covered here will be secure, useful, and valid, but it's just the tip of the proverbial iceberg.
Encrypting Data
With MCrypt libraries 2.4.x and higher, you start by identifying which algorithm and mode to use by invoking the mcrypt_module_open() function:
$m = mcrypt_module_open (algorithm, algorithm_directory, mode, mode_directory);
MCrypt comes with dozens of different algorithms, or ciphers, each of which encrypts data differently. If you are interested in how each works, see the MCrypt home page or search the Web. In my examples, I'll be using the Rijndael algorithm, also known as the Advanced Encryption Standard (AES). It's a very popular and secure encryption algorithm, even up to United States government standards. I'll be using it with 256-bit keys, for extra security.
As for the mode, there are four main modes: ECB (electronic codebook), CBC (cipher block chaining), CFB (cipher feedback), and OFB (output feedback). CBC will suit most of your needs, especially when encrypting blocks of text as in this example. So to indicate that you want to use Rijndael 256 in CBC mode, you would code:
$m = mcrypt_module_open('rijndael-256', '', 'cbc', '');
The second and fourth arguments fed to the mcrypt_module_open() function are for explicitly stating where PHP can find the algorithm and mode files. These are not required unless PHP is unable to find a cipher and you know for certain it is installed.
Once the module is open, you create an IV (initialization vector). This may be required, optional, or unnecessary depending upon the mode being used. I'll use it with CBC, to increase the security. Here's how the PHP manual recommends an IV be created:
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($m), MCRYPT_DEV_RANDOM);
By using the mcrypt_enc_get_iv_size() function, a properly sized IV will be created for the cipher being used. Note that on Windows, you should use MCRYPT_RAND instead of MCRYPT_DEV_RANDOM, and call the srand() function before this line to ensure the random generation.
The final step before you are ready to encrypt data is to create the buffers that MCrypt needs to perform encryption:
mcrypt_generic_init ($m, $key, $iv);
The second argument is a key, which should be a hard-to-guess string. The key must be of a particular length, corresponding to the cipher you use. The Rijndael cipher I'm using takes a 256-bit key. Divide 256 by 8 (because there are 8 bits in a byte and each character in the key string takes one byte) and you'll see that the key needs to be exactly 32 characters long. To accomplish that, and to randomize the key even more, I'll run it through MD5(), which always returns a 32-character string:
$key = MD5('some string');
Once you have gone through these steps, you are ready to encrypt data:
$encrypted_data = mcrypt_generic ($m, $data);
Finally, after you have finished encrypting everything, you should close all the buffers and modules:
mcrypt_generic_denit ($m); mcrypt_module_close($m);
For this example, I'm going to create a cookie whose value is encrypted. The cookie data will be decrypted in the next example. The key and data to be encrypted will be hard-coded into this script, but I'll mention alternatives in the following steps. Also, because the same key and IV are needed to decrypt the data, the IV will also be sent in a cookie. Surprisingly, doing so doesn't hurt the security of the application.
To encrypt data
- Begin a new PHP script in your text editor or IDE (Script 4.5).
<?php # Script 4.5 - set_mcrypt_cookie.php
Because the script will send two cookies, most of the PHP code will come before any HTML. Define the key and the data.
$key = md5('77 public drop-shadow Java'); $data = 'rosebud';
For the key, some random words and numbers are run through the MD5() function, creating a 32-character-long string. Ideally, the key should be stored in a safe place, such as a configuration file located outside of the Web document root. Or it could be retrieved from a database.
The data being encrypted is the word rosebud, although in real applications this data might come from the database or another source (and be something more worth protecting).
- Open the cipher.
$m = mcrypt_module_open('rijndael-256', '', 'cbc', '');
This is the same code outlined in the text before these steps.Script 4.5. This script uses MCrypt to encrypt some data to be stored in a cookie.
1 <?php # Script 4.5 - set_mcrypt_cookie.php 2 3 /* This page uses the MCrypt library 4 * to encrypt some data. 5 * The data will then be stored in a cookie, 6 * as will the encryption IV. 7 */ 8 9 // Create the key: 10 $key = md5('77 public drop-shadow Java'); 11 12 // Data to be encrypted: 13 $data = 'rosebud'; 14 15 // Open the cipher: 16 // Using Rijndael 256 in CBC mode. 17 $m = mcrypt_module_open('rijndael-256', '', 'cbc', ''); 18 19 // Create the IV: 20 // Use MCRYPT_RAND on Windows instead of MCRYPT_DEV_RANDOM. 21 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($m), MCRYPT_DEV_RANDOM); 22 23 // Initialize the encryption: 24 mcrypt_generic_init($m, $key, $iv); 25 26 // Encrypt the data: 27 $data = mcrypt_generic($m, $data); 28 29 // Close the encryption handler: 30 mcrypt_generic_deinit($m); 31 32 // Close the cipher: 33 mcrypt_module_close($m); 34 35 // Set the cookies: 36 setcookie('thing1', base64_encode($data)); 37 setcookie('thing2', base64_encode($iv)); 38 ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 39 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 40 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 41 <head> 42 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> 43 <title>A More Secure Cookie</title> 44 </head> 45 <body> 46 <p>The cookie has been sent. Its value is '<?php echo base64_encode($data); ?>'.</p> 47 </body> 48 </html>
- Create the IV.
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($m), MCRYPT_DEV_RANDOM);
Again, this is the same code outlined earlier. Remember that if you are running this script on Windows, you'll need to change this line to:srand(); $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($m), MCRYPT_RAND);
- Initialize the encryption.
mcrypt_generic_init($m, $key, $iv);
- Encrypt the data.
$data = mcrypt_generic($m, $data);
If you were to print the value of $data now, you'd see something like Figure 4.17.Figure 4.17 This gibberish is the encrypted data in binary form.
- Perform the necessary cleanup.
mcrypt_generic_deinit($m); mcrypt_module_close($m);
Send the two cookies.
setcookie('thing1', base64_encode($data)); setcookie('thing2', base64_encode($iv));
For the cookie names, I'm using meaningless values. You certainly wouldn't want to use, say, IV, as a cookie name! For the cookie data itself, you have to run it through base64_encode() to make it safe to store in a cookie. This applies to both the encrypted data and the IV (which is also in binary format).
If the data were going to be stored in a binary file or in a database (in a BLOB column), you wouldn't need to use base64_encode().
- Add the HTML head.
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>A More Secure Cookie</title> </head> <body>
- Print a message, including the encoded, encrypted version of the data.
<p>The cookie has been sent. Its value is '<?php echo base64_encode($data); ?>'.</p>
I'm doing this mostly so that the page shows something (Figure 4.18), but also so that you can see the value stored in the cookie.Figure 4.18 The result of running the page.
- Complete the page.
</body> </html>
Save the file as set_mcrypt_cookie.php, place it in your Web directory, and test in your Web browser.
If you set your browser to show cookies being sent, you'll see the values when you run the page (Figures 4.19 and 4.20).
Figure 4.19 The first cookie stores the actual data.
Figure 4.20 The second cookie stores the base64_encode() version of the IV.
Decrypting Data
When it's time to decrypt encrypted data, most of the process is the same as it is for encryption. To start:
$m = mcrypt_module_open('rijndael-256', '', 'cbc', ''); mcrypt_generic_init($m, $key, $iv);
At this point, instead of using mcrypt_generic(), you'll use mdecrypt_generic():
$data = mdecrypt_generic($m, $encrypted_data);
Note, and this is very important, that to successfully decrypt the data, you'll need the exact same key and IV used to encrypt it.
Once decryption has taken place, you can close up your resources:
mcrypt_generic_deinit($m); mcrypt_module_close($m);
Finally, you'll likely want to apply the rtrim() function to the decrypted data, as the encryption process may add white space as padding to the end of the data.
To decrypt data
- Begin a new PHP script in your text editor or IDE, starting with the HTML (Script 4.6).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>A More Secure Cookie</title> </head> <body> <?php # Script 4.6 - read_mcrypt_cookie.php
Script 4.6. This script reads in a cookie with encrypted data (plus a second cookie that stores an important piece for decryption); then it decrypts and prints the data.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 4 <head> 5 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> 6 <title>A More Secure Cookie</title> 7 </head> 8 <body> 9 <?php # Script 4.6 - read_mcrypt_cookie.php 10 11 /* This page uses the MCrypt library 12 * to decrypt data stored in a cookie. 13 */ 14 15 // Make sure the cookies exist: 16 if (isset($_COOKIE['thing1']) && isset($_COOKIE['thing2'])) { 17 18 // Create the key: 19 $key = md5('77 public drop-shadow Java'); 20 21 // Open the cipher: 22 // Using Rijndael 256 in CBC mode. 23 $m = mcrypt_module_open('rijndael-256', '', 'cbc', ''); 24 25 // Decode the IV: 26 $iv = base64_decode($_COOKIE['thing2']); 27 28 // Initialize the encryption: 29 mcrypt_generic_init($m, $key, $iv); 30 31 // Decrypt the data: 32 $data = mdecrypt_generic($m, base64_decode($_COOKIE['thing1'])); 33 34 // Close the encryption handler: 35 mcrypt_generic_deinit($m); 36 37 // Close the cipher: 38 mcrypt_module_close($m); 39 40 // Print the data. 41 echo '<p>The cookie has been received. Its value is "' . trim($data) . '".</p>'; 42 43 } else { // No cookies! 44 echo '<p>There\'s nothing to see here.</p>'; 45 } 46 ?> 47 </body> 48 </html>
- Check that the cookies exist.
if (isset($_COOKIE['thing1']) && isset($_COOKIE['thing2'])) {
There's no point in trying to decrypt the data if the page can't read the two cookies. - Create the key.
$key = md5('77 public drop-shadow Java');
Not to belabor the point, but again, this must be the exact same key used to encrypt the data. This is another reason why you might want to store the key outside of these scripts. - Open the cipher.
$m = mcrypt_module_open('rijndael-256', '', 'cbc', '');
This should also match the encryption code (you have to use the same cipher and mode for both encryption and decryption). - Decode the IV.
$iv = base64_decode ($_COOKIE['thing2']);
The IV isn't being generated here; it's being retrieved from the cookie (because it has to be the same IV as was used to encrypt the data). The base64_decode() function will return the IV to its binary form. - Initialize the decryption.
mcrypt_generic_init($m, $key, $iv);
- Decrypt the data.
$data = mdecrypt_generic($m, base64_decode($_COOKIE['thing1']));
The mdecrypt_generic() function will decrypt the data. The data is coming from the cookie and must be decoded first. - Wrap up the MCrypt code.
mcrypt_generic_deinit($m); mcrypt_module_close($m);
- Print the data.
echo '<p>The cookie has been received. Its value is "' . trim($data) . '".</p>';
- Complete the page.
} else { echo '<p>There\'s nothing to see here.</p>'; } ?> </body> </html>
The else clause applies if the two cookies were not accessible to the script. - Save the file as read_mcrypt_cookie.php, place it in your Web directory, and test in your Web browser (Figure 4.21).
Figure 4.21 The cookie data has been successfully decrypted.