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

Create a Cryptography Class

(Appendix C, Cryptography - Pg 99-100)

< Back to Code Repository

<?php

class crypt
{
    private 
$algorithm;
    private 
$mode;
    private 
$random_source;

    public 
$cleartext;
    public 
$ciphertext;
    public 
$iv;

    public function 
__construct($algorithm = MCRYPT_BLOWFISH,
                                
$mode = MCRYPT_MODE_CBC,
                                
$random_source = MCRYPT_DEV_URANDOM)
    {
        
$this->algorithm = $algorithm;
        
$this->mode = $mode;
        
$this->random_source = $random_source;
    }

    public function 
generate_iv()
    {
        
$this->iv = mcrypt_create_iv(mcrypt_get_iv_size($this->algorithm,
                    
$this->mode), $this->random_source);
    }

    public function 
encrypt()
    {
        
$this->ciphertext = mcrypt_encrypt($this->algorithm,
                            
$_SERVER['CRYPT_KEY'], $this->cleartext,
                            
$this->mode, $this->iv);
    }

    public function 
decrypt()
    {
        
$this->cleartext = mcrypt_decrypt($this->algorithm,
                           
$_SERVER['CRYPT_KEY'], $this->ciphertext,
                           
$this->mode, $this->iv);
    }
}

?>