November 2002
Intermediate to advanced
640 pages
16h 33m
English
You want to store encrypted data that needs to be retrieved and decrypted later by your web server.
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);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); ...Read now
Unlock full access