Essential PHP Security Book Cover
Essential PHP Security by Chris Shiflett
About | Contents | Buy Now | Reviews | Errata | Code
  1. Foreword
  2. Preface
  1. Introduction
  2. Forms and URLs
          ch02.pdf
  3. Databases and SQL
  4. Sessions and Cookies
          ch04.pdf
  5. Includes
  6. Files and Commands
  7. Authentication and Authorization
  8. Shared Hosting
  1. Configuration Directives
  2. Functions
  3. Cryptography
  4. Index

Encrypt Session Data

(Appendix C, Cryptography - Pg 102-103)

< Back to Code Repository

<?php

function _read($id)
{
    global 
$_sess_db;

    
$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($data0$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);
}

?>