1.14 Encrypting a String


You want to encrypt or decrypt a string.

Technique

You can write your own encryption/decryption routine:

 <?php function encrypt_data ($data, $passwd) {     for ($i = 0, $j = 0; $i < strlen ($data); $i++, $j++) {         $middle = ord(substr($data,$i,1)) +                   ord(substr($passwd,$j,1));         if ($j > strlen($passwd)) {  $j=0; }         $estr .= chr ($middle);      }     return ($estr); } function decrypt_data ($data, $passwd) {     for ($i = 0, $j = 0; $i < strlen($data); $i++, $j++) {         $middle = ord (substr ($data, $i, 1)) -                         ord (substr ($passwd, $j, 1));         if ( $j > strlen ($passwd) ) {  $j=0; }         $estr .= chr ($middle);     }     return ($estr); } ?> 

This is one of the simplest forms of encryption. It is almost as insecure as regular, unencrypted data. You are better off using PHP's built-in functions for encryption and decryption (this will work if you have mcrypt support compiled in). Here is an example using TripleDES encryption:

 <?php $key = "Sterling Hughes"; $string = "Super Secretive, Super Classified Information"; $encrypted_data = mcrypt_ecb(MCRYPT_TripleDES, $key, $string, MCRYPT_ENCRYPT); $decrypted_data = mcrypt_ecb(MCRYPT_TripleDES, $key, $string, MCRYPT_DECRYPT); ?> 

Comments

These built-in encryption functions work with the mcrypt library that can be found at ftp://argeas.cs-net.gr/pub/unix/mcrypt/.

The ability to encrypt data is very useful, especially when you are running an e-commerce Web site and need to encrypt information such as credit card numbers and Social Security numbers. The same situation comes up with banks; banks are required by United States law to encrypt sensitive data such as bank IDs, Social Security numbers , and more.

If you are looking for one-way encryption (you can encrypt the data but you can't decrypt it), you can use PHP's standard crypt() function. Given the same data, crypt() will give you the same encrypted result, but you can't ever get back the original data.

 <?php // $data1 and $data2 are submitted if (!strcmp ($data1, $data2)) {     print "$data1 and $data2 are the same before encryption\n"; } else {     print "$data1 and $data2 are different before encryption\n"; } $data1 = crypt ($data1, substr ($data1, 0, 2)); $data2 = crypt ($data2, substr ($data2, 0, 2)); if (!strcmp ($data1, $data2)) {     print "What dya know they're the same after encryption!"; } else {     print "Still different after the encryption!"; } ?> 

PHP also provides the md5() function, which has a stronger one-way hash algorithm than the crypt() function:

 <?php $data = "Thanks for this idea Zak!"; $hashed_data = md5($data); print "The md5 hash of $data is $hashed_data"; ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net