Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

Security Techniques

This chapter is from the book

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 and configure PHP to support it (Figure 4.16)

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);

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

  1. 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.
  2. 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).

  3. 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
    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     */
    9    // Create the key:
    10   $key = md5('77 public drop-shadow Java');
    12   // Data to be encrypted:
    13   $data = 'rosebud';
    15   // Open the cipher:
    16   // Using Rijndael 256 in CBC mode.
    17   $m = mcrypt_module_open('rijndael-256', '', 'cbc', '');
    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);
    23   // Initialize the encryption:
    24   mcrypt_generic_init($m, $key, $iv);
    26   // Encrypt the data:
    27   $data = mcrypt_generic($m, $data);
    29   // Close the encryption handler:
    30   mcrypt_generic_deinit($m);
    32   // Close the cipher:
    33   mcrypt_module_close($m);
    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          "">
    40   <html xmlns="" 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>
  4. 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:
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($m), MCRYPT_RAND);
  5. Initialize the encryption.
    mcrypt_generic_init($m, $key, $iv);
  6. 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

    Figure 4.17 This gibberish is the encrypted data in binary form.

  7. Perform the necessary cleanup.
  8. 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().

  9. Add the HTML head.
    ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    <html xmlns="" xml:lang="en" lang="en">
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
        <title>A More Secure Cookie</title>
  10. 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

    Figure 4.18 The result of running the page.

  11. Complete the page.
  12. 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

    Figure 4.19 The first cookie stores the actual data.

    Figure 4.20

    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:


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

  1. 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"
    <html xmlns="" xml:lang="en" lang="en">
         <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
         <title>A More Secure Cookie</title>
    <?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           "">
    3    <html xmlns="" 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
    11   /*  This page uses the MCrypt library
    12    *  to decrypt data stored in a cookie.
    13    */
    15   // Make sure the cookies exist:
    16   if (isset($_COOKIE['thing1']) && isset($_COOKIE['thing2'])) {
    18       // Create the key:
    19       $key = md5('77 public drop-shadow Java');
    21       // Open the cipher:
    22       // Using Rijndael 256 in CBC mode.
    23       $m = mcrypt_module_open('rijndael-256', '', 'cbc', '');
    25       // Decode the IV:
    26       $iv = base64_decode($_COOKIE['thing2']);
    28       // Initialize the encryption:
    29       mcrypt_generic_init($m, $key, $iv);
    31       // Decrypt the data:
    32       $data = mdecrypt_generic($m, base64_decode($_COOKIE['thing1']));
    34       // Close the encryption handler:
    35       mcrypt_generic_deinit($m);
    37       // Close the cipher:
    38       mcrypt_module_close($m);
    40       // Print the data.
    41       echo '<p>The cookie has been received. Its value is "' . trim($data) . '".</p>';
    43   } else { // No cookies!
    44       echo '<p>There\'s nothing to see here.</p>';
    45   }
    46   ?>
    47   </body>
    48   </html>
  2. 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.
  3. 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.
  4. 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).
  5. 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.
  6. Initialize the decryption.
    mcrypt_generic_init($m, $key, $iv);
  7. 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.
  8. Wrap up the MCrypt code.
  9. Print the data.
    echo '<p>The cookie has been received. Its value is "' . trim($data) . '".</p>';
  10. Complete the page.
    } else {
        echo '<p>There\'s nothing to see here.</p>';
    The else clause applies if the two cookies were not accessible to the script.
  11. 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

    Figure 4.21 The cookie data has been successfully decrypted.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020