<?php
class cryptSession {
private $iv = false; // DONT CHANGE THIS
private $key = 'Secret key'; // YOUR SECRET KEY
// This word is original [$word]
// This word is encrypted and sent to the client like cookie
// The cookie is decrypted and compared to the original word
private $word = 'Secret words';
private $cookieLiveTime = 3600; // Lifetime of cookie
private $cookieDomain = 'your_domain.ru'; // Domain for cookie
// Construct function
public function __construct() {
// session start
@session_start();
// If var exists start verification function
if (key_exists('_val_',$_SESSION)) {
// If verification failed...
if (!$this->validateIV()) {
// you can do want you want (your code)
// My recomendations:
// Left the lines below with redirection to autorization form on your site
@session_destroy(); // Destroy session
header('location:/authorization_form.html'); // it is redirection to your authorization form
die(); // Die =(
}
// If verification is successful
// your code
else {}
}
}
// Generation crypt key
public function generateIV() {
// iv - sending to session and saving local on the server, it's unique for each user
$this->iv = $_SESSION['_val_'] = mcrypt_create_iv (mcrypt_get_iv_size (MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
// Encode original word and send to the client like cookie (as iv is unique so encoded word is unique for each as well)
$cookie = base64_encode(mcrypt_encrypt (MCRYPT_RIJNDAEL_256, $this->key, $this->word, MCRYPT_MODE_ECB, $this->iv));
setcookie('word',$cookie,time()+$this->cookieLiveTime,'/',$this->cookieDomain);
return true;
}
// Verification...
private function validateIV() {
// Using iv from client session...
$this->iv = $_SESSION['_val_'];
// Using client cookie (which is encrypted word)...
$userCookie = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->key, base64_decode($_COOKIE['word']), MCRYPT_MODE_ECB, $this->iv);
// Validate client decrypted word (from cookie) with original word
// if it is true - return TRUE, othervise FALSE
if (str_replace("\0",'',$userCookie) === $this->word) {
// Start again new secret word and iv generation
$this->generateIV();
return true;
}
else return false;
}
}
?>