PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Subscribe to PHP Subscribe to Newsletters

PHP's Encryption Functionality
Pages: 1, 2, 3

Mcrypt

Mcrypt version 2.4.7 is a powerful encryption library containing 22 block algorithms. Specifically, the following algorithms are supported:

Blowfish RC2 Safer-sk64 xtea
Cast-256 RC4 Safer-sk128
DES RC4-iv Serpent
Enigma Rijndael-128 Threeway
Gost Rijndael-192 TripleDES
LOKI97 Rijndael-256 Twofish
Panama Saferplus Wake

Installation

Mcrypt isn't included in the standard PHP distribution, so you'll need to download it. You can get the latest distribution from ftp://argeas.cs-net.gr/pub/unix/mcrypt/. After you've successfully downloaded the most recent distribution, follow these steps to compile Mcrypt and build the extension into your PHP distribution:



  1. Download the Mcrypt library
  2. gunzip mcrypt-x.x.x.tar.gz
  3. tar -xvf mcrypt-x.x.x.tar
  4. ./configure --disable-posix-threads
  5. make
  6. make install
  7. cd to your PHP directory.
  8. ./configure -with-mcrypt=[dir] [--other-configuration-directives]
  9. make
  10. make install

Of course, depending on your own requirements and the way PHP is installed in relation to your web server, you may need to modify this configuration process.

Working with Mcrypt

Mcrypt is particularly useful not only for the number of encryption algorithms it offers the user, but also because it can be used to encrypt and decrypt data. Furthermore, PHP's Mcrypt extension offers 35 rather useful functions manipulating data. Although a complete discussion of these functions is out of the scope of this article, I'll introduce several of the more prominent ones in this section.

To begin, I'll introduce how data can be encrypted and then later decrypted using the Mcrypt extension. Listing 4 demonstrates this, first encrypting a string, then displaying the encrypted data to the browser, and then decrypting that string and again displaying it in its original format.


Listing 4: Encrypting and decrypting data with Mcrypt.

<?php

// Designate string to be encrypted
$string = "Applied Cryptography, by Bruce Schneier, is 
a wonderful cryptography reference.";

// Encryption/decryption key
$key = "Four score and twenty years ago";

// Encryption Algorithm
$cipher_alg = MCRYPT_RIJNDAEL_128;

// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, 
MCRYPT_MODE_ECB), MCRYPT_RAND);

// Output original string
print "Original string: $string <p>";

// Encrypt $string
$encrypted_string = mcrypt_encrypt($cipher_alg, $key, 
$string, MCRYPT_MODE_CBC, $iv);

// Convert to hexadecimal and output to browser
print "Encrypted string: ".bin2hex($encrypted_string)."<p>";

$decrypted_string = mcrypt_decrypt($cipher_alg, $key, 
$encrypted_string, MCRYPT_MODE_CBC, $iv);

print "Decrypted string: $decrypted_string";

?>

Executing Listing 4 will produce the following output:

Original string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.

Encrypted string: 02a7c58b1ebd22a9523468694b091e60411cc4dea8652bb8072 34fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b c89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 bfbab5e

Decrypted string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.

It's likely that the two most prominent functions in Listing 4 are mcrypt_encrypt() and mcrypt_decrypt(), the utility of each being obvious. I use the mode known as "Electronic Codebook Mode." Mcrypt offers several encryption modes, all worth examining because each has specific characteristics that can influence the security of the cipher. For those of you new to the world of cryptography, you may be curious to learn more about the function mcrypt_create_iv(). While a thorough explanation is out of the scope of this article, I will mention that this function creates an initialization vector (hence, iv), which makes each message unique. While the initialization vector is not used in every mode, PHP will complain if it is not used along with those in which it is required (cbc, cfb, and ofb modes).

Mhash

The Mhash library extension provides support to 12 hashing algorithms (as of version 0.8.3). An examination of the Mhash v.0.8.3 header file (mhash.h) shows that it supports the following hashing algorithms:

CRC32 HAVAL160 MD5
CRC32B HAVAL192 RIPEMD160
GOST HAVAL224 SHA1
HAVAL128 HAVAL256 TIGER

As you can see, there are many hashing algorithms to choose from.

Installation

Like Mcrypt, Mhash is not included in the default PHP distribution. You can download it. For non-Windows users, here is the installation process:

  1. Download the Mhash library
  2. gunzip mhash-x.x.x.tar.gz
  3. tar -xvf mhash-x.x.x.tar
  4. ./configure
  5. make
  6. make install
  7. cd to your PHP directory.
  8. ./configure -with-mhash=[dir] [--other-configuration-directives]
  9. make
  10. make install

Again, depending upon how PHP is installed in relation to your Web server, you may have to perform extra configuration steps.

For Windows users, you may be interested to know that http://www.php4win.de offers a great Win32 PHP distribution packed with the Mhash extension included. Just download and unzip the distribution, and follow the directions found in the readme.first document.

Working with Mhash

Hashing a message is easy. Consider the following example:

<?php
$hash_alg = MHASH_TIGER;
$message = "These are the directions to the 
secret fort. Two steps left, three steps 
right, and cha cha cha.";
$hashed_message = mhash($hash_alg, $message);
print "The hashed message is ". bin2hex($hashed_message);
?>

Executing this script will yield the outcome:

The hashed message is 07a92a4db3a4177f19ec9034ae5400eb60d1a9fbb4ade461

Notice that the function bin2hex() is used to facilitate the output of $hashed_message. This is because the hashed outcome is in binary format, and must be converted to hexadecimal in order to be converted to a readable format.

Remember that because the hash is a one-way function and its output is not dependent upon the input, you could display this message in public view. In fact, this strategy is commonly used to allow users to compare message digests of downloaded files with those provided by the system administrator to ensure that they have not been corrupted or compromised.

Mhash also offers a few other useful functions. For example, suppose I wanted to output the name of a particular Mhash supported hashing algorithm. Based on the premise that Mhash assumes all supported algorithms begin with MHASH_, I could execute the following:

<?php
$hash_alg = MHASH_TIGER;

print "This data has been hashed with the 
".mhash_get_hash_name($hashed_message)."
 hashing algorithm.";
?>

And the resulting output:

This data has been hashed with the TIGER hashing algorithm.

A final note about PHP and encryption

One final very important note to make about PHP and encryption is that any data transmitted between the server and the client (and vice-versa) is not secure while in transit! PHP is a server-side technology, and can do nothing to prevent snoopers from watching this data in transit. Therefore, if you are interested in implementing a complete security application, I would suggest checking out Apache-SSL, or any of the other reputable secure-server implementations.

Conclusion

This article introduced one of PHP's particularly cool functions: data encryption. I discussed not only PHP's built-in crypto-functions (namely crypt() and md5()), but also introduced the two powerful extensions -- Mcrypt and Mhash. In closing, I'd like to point out that a truly secure PHP implementation would most likely involve the use of a secure server. PHP is a server-side language and therefore cannot protect data as it travels from the client to the server.

Resources

If you are interested in learning more about encryption, take some time to check out the following resources:

  • Applied Cryptography: Protocols, Algorithms and Source Code in C, by Bruce Schneier. John Wiley & Sons, 1996.
  • RSA Security
  • Attrition.org
  • Cryptome
  • Ronald L. Rivest's Cryptography and Security Site
  • Tom Dunigan's Security page

W.J. Gilmore has been developing PHP applications since 1997, and is frequently published on the subject within some of the Web's most popular development sites. He is the author of 'A Programmer's Introduction to PHP 4.0' (January 2001, Apress), and is the Assistant Editorial Director of Web and Open Source Technologies at Apress.


Return to the PHP DevCenter.




Tagged Articles

Post to del.icio.us

This article has been tagged:

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

encryption

Articles that share the tag encryption:

Secure RSS Syndication (104 tags)

PHP's Encryption Functionality (21 tags)

Encrypting Connection Strings in Web.config (5 tags)

Creating Your Own CA (4 tags)

How to Set Up Encrypted Mail on Mac OS X (3 tags)

View All

security

Articles that share the tag security:

Secure RSS Syndication (169 tags)

Google Your Site For Security Vulnerabilities (74 tags)

Building a Desktop Firewall (64 tags)

The Next 50 Years of Computer Security: An Interview with Alan Cox (42 tags)

Protect Yourself from WiFi Snoops (40 tags)

View All

programming

Articles that share the tag programming:

Rolling with Ruby on Rails (1374 tags)

Very Dynamic Web Interfaces (279 tags)

Ajax on Rails (231 tags)

Understanding MVC in PHP (202 tags)

A Simpler Ajax Path (186 tags)

View All

development

Articles that share the tag development:

Rolling with Ruby on Rails (579 tags)

What Is Web 2.0 (129 tags)

Ajax on Rails (119 tags)

Very Dynamic Web Interfaces (97 tags)

Understanding MVC in PHP (64 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com