Created
May 5, 2015 18:08
-
-
Save wopot/94e33bdd1d7faaaa56e2 to your computer and use it in GitHub Desktop.
Fork of Example https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly in defuse/php-encryption
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ?