O'Reilly logo

PHP Cookbook by Adam Trachtenberg, David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.8. Storing Encrypted Data in a File or Database

Problem

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

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

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required