Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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);
}
@TonioParis

This comment has been minimized.

Show comment
Hide comment
@TonioParis

TonioParis Jul 3, 2015

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 ?

TonioParis commented Jul 3, 2015

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

This comment has been minimized.

Show comment
Hide comment

maop commented Jul 10, 2015

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