advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Rate this item | 0 users have rated this item.
 Print Print
 
A Guide to Cryptography in PHP
This comprehensive guide discusses where to get, how to install, and how to use the various cryptography packages available to enhance the security of your PHP applications. 

advertisement
n an ideal world, words like cryptography and security wouldn't even exist, but the real world is far from perfect, so software developers have to spend a good deal of time building security into applications. Cryptography is just one piece of the security puzzle, along with SSL/TLS, certificates, digital signatures, and so on. This article explains how to use PHP to implement the most common cryptographic algorithms. In addition to describing PHP's default encryption functions, you'll see how to use a wide variety of cryptographic libraries and packages.

The code examples in this article use the contents of a short text file, textfile.txt, which contains the following plain-text content:

   For every difficult and complicated 
   question there is an answer 
   that is simple, easily understood, 
   and wrong. H.L. Mencken
Default PHP Encryption Functions
PHP ships with three built-in encryption functions: md5(), crypt(), and sha1(). The md5() function prototype is:

   string md5(string $str [, bool $raw_output ])
The function calculates the MD5 hash of a supplied string using the MD5 Message-Digest algorithm. The $str argument represents the string to be encrypted. If you pass FALSE in the $raw_output argument (the default), the function returns the hash as a 32-character hexadecimal number. If you pass TRUE then the function returns a 16-byte raw binary value.

The PHP crypt() function is a one-way encryption function that lets you confirm that an entered password matches a stored encrypted one—without having to decrypt anything. The crypt() function prototype is:

   string crypt (string $str [, string $salt ])
It returns an encrypted string using the standard Unix DES-based encryption algorithm (or alternative algorithms that may be available on the system). The $str argument is the string to be encrypted and the optional $salt argument is a string on which to base the encryption. If you don't provide the salt string, PHP will randomly generate one each time you call this function.

The PHP sha1() function calculates the SHA-1 hash of a string. The sha1() function prototype is:

   string sha1 (string $str [, bool $raw_output ])
 
Figure 1. Encrypted File: The encrypted.txt file contains a password encrypted with md5, crypt, and sha1 PHP default functions.
The function returns the SHA-1 hash as a string. Again, the $str argument represents the input string. If you set the optional $raw_output argument to TRUE, the function returns the sha1 hash in raw binary format with a length of 20 characters; if you set it to FALSE, it returns a 40-character hexadecimal number.

As an example, the following code shows how to use the PHP default encryption functions to encrypt the contents of texfile.txt file and write the encrypted result in the file encrypted.txt (see Figure 1):

   <?php
    
   $file = 'textfile.txt';
   $initial_contents = file_get_contents($file);  
   
   if($initial_contents){
   
      $password = 'OctaviaAnghel';
   
      //Calculates the md5 hash 
      $md5_data = md5($password);
   
      //This function encrypts data
      $crypt = crypt($password);
   
      //Calculate the sha1 hash
      $sha1 = sha1($password);
   
      $encrypted_file = @fopen('encrypted.txt','w');
      $ok_encrypt = @fwrite($encrypted_file,'md5: '. $md5_data."\r\n".'crypt: 
          '.$crypt."\r\n".'sha1: '.$sha1);
   
      if($ok_encrypt){
         echo 'The encrypted code was succesfully created'.
         ' in encrypted_file.txt!!!'.'
'; } else{ echo ("The write of this file failed!"); } @fclose($encrypted_file); } ?>
In addition to the built-in functions, PHP supports encryption via external libraries and packages. Table 1 shows the libraries and packages described in the rest of this article.

Table 1. Cryptography in PHP: The table contains a list of packages and libraries described in this article that work with PHP to perform various types of encryption and decryption.
Package/Library Description
MCrypt Use MCrypt to encrypt large files or data streams using any of a wide range of encryption functions. You can find more information at http://mcrypt.sourceforge.net/.
MHash Use the MHash library to obtain hashes. MHash supports the most popular algorithms and implementations, such as SHA, MD5, and CRC. You can use these algorithms to compute checksums, message digests, and create other signatures. MHash is often used to obtain password hashes for passwords entered into HTML password fields. You can find more information at http://mhash.sourceforge.net/.
Crypt_Blowfish Use Crypt_Blowfish for quick two-way encryption both with or without a secret key. You don't need the MCrypt PHP extension to use Crypt_Blowfish; however, the package can use MCrypt if it's installed. More details at: http://pear.php.net/package/Crypt_Blowfish.
Crypt_RSA Crypt_RSA provides RSA-like key generation, encryption/decryption, signing and signature checking. More details here: http://pear.php.net/package/Crypt_RSA.
Crypt_ HMAC This class calculates RFC 2104-compliant hashes. You'll find complete information at: http://pear.php.net/package/Crypt_HMAC.
Crypt_DiffieHellman This package is a PHP5 implementation of the Diffie-Hellman Key Exchange cryptographic protocol. You can find more information at http://pear.php.net/package/Crypt_DiffieHellman.

  Next Page: Encrypting Large Data with MCrypt
Page 1: IntroductionPage 4: Using the Crypt_RSA PEAR Package
Page 2: Encrypting Large Data with MCryptPage 5: Generating Secret Keys with the Crypt_DiffieHellman PEAR Package
Page 3: Building Hashes with MHash 
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM eBook: Planning a Service Oriented Architecture
IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
Intel Go Parallel Article: Getting Started with TBB on Windows
Microsoft Article: 7.0, Microsoft's Lucky Version?
Avaya Article: How to Feed Data into the Avaya Event Processor
IBM Article: Developing a Software Policy for Your Organization
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Go Parallel Article: Intel Threading Tools and OpenMP
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
IBM Article: Enterprise Search--Do You Know What's Out There?
HP Demo: StorageWorks EVA4400
Microsoft Article: The Progress and Promise of Deep Zoom
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES