C.4. Encrypting Session Data
If the security of your database is in question, or if the data that you store in sessions is particularly sensitive, you might wish to encrypt all session data. I do not recommend this approach unless absolutely necessary, but if you feel that your situation warrants it, this section provides an example implementation.
The idea is pretty simple. In fact, in Chapter 8, you are shown how to implement your own session mechanism by calling session_set_save_handler( ). With a minor adjustment to the functions that store and retrieve data, you can encrypt data that you store in the database and decrypt the data that you retrieve:
<?php
function _read($id)
{
global $_sess_db;
$algorithm = MCRYPT_BLOWFISH;
$mode = MCRYPT_MODE_CBC;
$id = mysql_real_escape_string($id);
$sql = "SELECT data
FROM sessions
WHERE id = '$id'";
if ($result = mysql_query($sql, $_sess_db))
{
$record = mysql_fetch_assoc($result);
$data = base64_decode($record['data']);
$iv_size = mcrypt_get_iv_size($algorithm, $mode);
$ciphertext = substr($data, $iv_size);
$iv = substr($data, 0, $iv_size);
$crypt = new crypt();
$crypt->iv = $iv;
$crypt->ciphertext = $ciphertext;
$crypt->decrypt();
return $crypt->cleartext;
}
return '';
}
function _write($id, $data)
{
global $_sess_db;
$access = time();
$crypt = new crypt();
$crypt->cleartext = $data;
$crypt->generate_iv();
$crypt->encrypt();
$ciphertext = $crypt->ciphertext;
$iv = $crypt->iv;
$data = base64_encode($iv . $ciphertext);
$id = mysql_real_escape_string($id);
$access = mysql_real_escape_string($access);
$data = mysql_real_escape_string($data);
$sql = "REPLACE
INTO sessions
VALUES ('$id', '$access', '$data')";
return mysql_query($sql, $_sess_db);
}
|