PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 14.9 Storing Encrypted Data in a File or Database

14.9.1 Problem

You want to store encrypted data that needs to be retrieved and decrypted later by your web server.

14.9.2 Solution

Store the additional information required to decrypt the data (such as algorithm, cipher mode, and initialization vector) along with the encrypted information, but not the key:

// encrypt data
$alg  = MCRYPT_BLOWFISH;
$mode = MCRYPT_MODE_CBC;
$iv = mcrypt_create_iv(mcrypt_get_iv_size($alg,$mode),MCRYPT_DEV_URANDOM);
$ciphertext = mcrypt_encrypt($alg,$_REQUEST['key'],$_REQUEST['data'],$mode,$iv);

// save encrypted data
$dbh->query('INSERT INTO noc_list (algorithm,mode,iv,data) values (?,?,?,?)',
            array($alg,$mode,$iv,$ciphertext));

To decrypt, retrieve a key from the user and use it with the saved data:

$row = $dbh->getRow('SELECT * FROM noc_list WHERE id = 27');
$plaintext = mcrypt_decrypt($row->algorithm,$_REQUEST['key'],$row->data,
                            $row->mode,$row->iv);

14.9.3 Discussion

The save-crypt.php program shown in Example 14-2 stores encrypted data to a file.

Example 14-2. save-crypt.php
function show_form() {
    print<<<_FORM_
<form method="post" action="$_SERVER[PHP_SELF]">
<textarea name="data" rows="10" cols="40">
Enter data to be encrypted here.
</textarea>
<br>
Encryption Key: <input type="text" name="key">
<input name="submit" type="submit" value="save">
</form>
_FORM_;
}

function save_form() {
    $alg  = MCRYPT_BLOWFISH;
    $mode = MCRYPT_MODE_CBC;

    // encrypt data
    $iv = mcrypt_create_iv(mcrypt_get_iv_size($alg,$mode),MCRYPT_DEV_URANDOM);
    $ciphertext = mcrypt_encrypt($alg, $_REQUEST['key'], 
                                 $_REQUEST['data'], $mode, $iv);
    
    // save encrypted data
    $filename = tempnam('/tmp','enc') or die($php_errormsg);
    $fh = fopen($filename,'w')        or die($php_errormsg);
    if (false === fwrite($fh,$iv.$ciphertext)) {
        fclose($fh);
        die($php_errormsg);
    }
    fclose($fh)                       or die($php_errormsg);

    return $filename;
}

if ($_REQUEST['submit']) {
    $file = save_form();
    print "Encrypted data saved to file: $file";
} else { 
    show_form();
}

Example 14-3 shows the corresponding program, get-crypt.php , that accepts a filename and key and produces the decrypted data.

Example 14-3. get-crypt.php
function show_form() {
    print<<<_FORM_
<form method="post" action="$_SERVER[PHP_SELF]">
Encrypted File: <input type="text" name="file">
<br>
Encryption Key: <input type="text" name="key">
<input name="submit" type="submit" value="display">
</form>
_FORM_;
}

function display() {
    $alg  = MCRYPT_BLOWFISH;
    $mode = MCRYPT_MODE_CBC;

    $fh = fopen($_REQUEST['file'],'r') or die($php_errormsg);
    $iv = fread($fh,mcrypt_get_iv_size($alg,$mode));
    $ciphertext = fread($fh,filesize($_REQUEST['file']));
    fclose($fh);

    $plaintext = mcrypt_decrypt($alg,$_REQUEST['key'],$ciphertext,$mode,$iv);
    print "<pre>$plaintext</pre>";
}

if ($_REQUEST['submit']) {
    display();
} else { 
    show_form();
}

These two programs have their encryption algorithm and mode hardcoded in them, so there's no need to store this information in the file. The file consists of the initialization vector immediately followed by the encrypted data. There's no need for a delimiter after the initialization vector (IV), because mcrypt_get_iv_size( ) returns exactly how many bytes the decryption program needs to read to get the whole IV. Everything after that in the file is encrypted data.

Encrypting files using the method in this recipe offers protection if an attacker gains access to the server on which the files are stored. Without the appropriate key or tremendous amounts of computing power, the attacker won't be able to read the files. However, the security that these encrypted file provides is undercut if the data to be encrypted and the encryption keys travel between your server and your users' web browsers in the clear. Someone who can intercept or monitor network traffic can see data before it even gets encrypted. To prevent this kind of eavesdropping, use SSL.

An additional risk when your web server encrypts data as in this recipe comes from how the data is visible before it's encrypted and written to a file. Someone with root or administrator access to the server can look in the memory the web server process is using and snoop on the unencrypted data and the key. If the operating system swaps the memory image of the web server process to disk, the unencrypted data might also be accessible in this swap file. This kind of attack can be difficult to pull off but can be devastating. Once the encrypted data is in a file, it's unreadable even to an attacker with root access to the web server, but if the attacker can peek at the unencrypted data before it's in that file, the encryption offers little protection.

14.9.4 See Also

Recipe 14.11 discusses SSL and protecting data as it moves over the network; documentation on mcrypt_encrypt( ) at http://www.php.net/mcrypt-encrypt, mcrypt_decrypt( ) at http://www.php.net/mcrypt-decrypt, mcrypt_create_iv( ) at http://www.php.net/mcrypt-create-iv, and mcrypt_get_iv_size( ) at http://www.php.net/mcrypt-get-iv-size.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    14.1 Introduction
    Recipe 14.2 Keeping Passwords Out of Your Site Files
    Recipe 14.3 Obscuring Data with Encoding
    Recipe 14.4 Verifying Data with Hashes
    Recipe 14.5 Storing Passwords
    Recipe 14.6 Checking Password Strength
    Recipe 14.7 Dealing with Lost Passwords
    Recipe 14.8 Encrypting and Decrypting Data
    Recipe 14.9 Storing Encrypted Data in a File or Database
    Recipe 14.10 Sharing Encrypted Data with Another Web Site
    Recipe 14.11 Detecting SSL
    Recipe 14.12 Encrypting Email with GPG
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele