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

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.