Skip to content

Instantly share code, notes, and snippets.

@wopot
Created May 5, 2015 18:08
Show Gist options
  • Save wopot/94e33bdd1d7faaaa56e2 to your computer and use it in GitHub Desktop.
Save wopot/94e33bdd1d7faaaa56e2 to your computer and use it in GitHub Desktop.
<?php
require_once('Crypto.php');
function setKey(){
try {
$key = Crypto::CreateNewRandomKey();
// WARNING: Do NOT encode $key with bin2hex() or base64_encode(),
// they may leak the key to the attacker through side channels.
} catch (CryptoTestFailedException $ex) {
die('Cannot safely create a key');
} catch (CannotPerformOperationException $ex) {
die('Cannot safely create a key');
}
return $key;
}
/**
* Store ciphertext in a cookie
*
* @param string $name - cookie name
* @param mixed $cookieData - cookie data
* @param string $key - crypto key
*/
function setSafeCookie($name, $cookieData, $key){
try {
$ciphertext = Crypto::Encrypt(json_encode($cookieData), $key);
} catch (CryptoTestFailedException $ex) {
die('Cannot safely perform encryption');
} catch (CannotPerformOperationException $ex) {
die('Cannot safely perform decryption');
}
return setcookie($name, $ciphertext);
}
/**
* Decrypt a cookie, expand to array
*
* @param string $name - cookie name
* @param string $key - crypto key
*/
function getSafeCookie($name, $key){
if (!isset($_COOKIE[$name])) {
return array();
}
$ciphertext = $_COOKIE[$name];
try {
$decrypted = Crypto::Decrypt($ciphertext, $key);
} catch (InvalidCiphertextException $ex) { // VERY IMPORTANT
// Either:
// 1. The ciphertext was modified by the attacker,
// 2. The key is wrong, or
// 3. $ciphertext is not a valid ciphertext or was corrupted.
// Assume the worst.
die('DANGER! DANGER! The ciphertext has been tampered with!');
} catch (CryptoTestFailedException $ex) {
die('Cannot safely perform encryption');
} catch (CannotPerformOperationException $ex) {
die('Cannot safely perform decryption');
}
if (empty($decrypted)) {
array();
}
return json_decode($decrypted, true);
}
@AnthonyDG
Copy link

I've dowloaded the .zip of 'defuse/php-encryption' and installed it (one week ago).

I just tried your script and I have this error :
Fatal error: Class 'Crypto' not found in /home/zideesdubj/www/_tests2enfants/_test_session/php-encryption-master/test.php on line XXX

Could you please help me ?

@maop
Copy link

maop commented Jul 10, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment