Skip to content

Instantly share code, notes, and snippets.

@mehdichaouch
Last active July 26, 2016 09:14
Show Gist options
  • Save mehdichaouch/fceedba86c33a102d360 to your computer and use it in GitHub Desktop.
Save mehdichaouch/fceedba86c33a102d360 to your computer and use it in GitHub Desktop.
PHP Snippet for Magento - Encrypt / Decrypt cookie
<?php
/**
* Mum ! I want complex cookie
*/
class Bonne_Maman_Helper_Data extends Mage_Core_Helper_Abstract
{
private static $secret = 'What is the answer to Life, the Universe, and Everything'; // Can be also a in conf
/**
* Encrypt the content of the cookie
*
* @param string $cookieName
* @param array $data
* @param string $lifetime
*/
public function createEncryptedCookie($cookieName = '', $data = array(), $lifetime = '')
{
try {
if (empty($cookieName) || is_null($cookieName)) {
Mage::throwException($this->__('Call to ' . __CLASS__ . ' without cookie name.'));
}
if (empty($data) || !is_array($data)) {
Mage::throwException($this->__('Call to ' . __CLASS__ . ' without $data or not array type.'));
}
if (empty($lifetime)) {
$lifetime = strtotime("+1 year");
}
$key = self::$secret;
$string = json_encode($data, JSON_FORCE_OBJECT);
// Encrypt
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encryptedData = base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv));
/** @var Mage_Core_Model_Cookie */
Mage::getModel('core/cookie')->set($cookieName, $encryptedData, $lifetime, '/');
} catch (Exception $e) {
Mage::getSingleton('core/session')->addWarning($e->getMessage());
Mage::logException($e);
return;
}
}
/**
* Return the content of encrypted cookie
*
* @param string $cookieName The cookie name
* @return stdClass $data Content of the cookie
*/
public function readEncryptedCookie($cookieName = '')
{
try {
if (empty($cookieName) || is_null($cookieName)) {
Mage::throwException($this->__('Call to ' . __METHOD__ . ' without cookie name.'));
}
$key = self::$secret;
/** @var Mage_Core_Model_Cookie $string */
$string = Mage::getModel('core/cookie')->get($cookieName);
// Decrypt
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$encrypted_dec = base64_decode($string);
$iv_dec = substr($encrypted_dec, 0, $iv_size);
$encrypted_dec = substr($encrypted_dec, $iv_size);
$decryptedData = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted_dec, MCRYPT_MODE_CBC, $iv_dec);
$data = json_decode(trim($decryptedData));
return $data;
} catch (Exception $e) {
if(isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])){
Mage::getSingleton('core/session')->addWarning($e->getMessage());
Mage::logException($e);
return;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment