Skip to content

Instantly share code, notes, and snippets.

@chrisveness
Created June 17, 2014 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisveness/f3f865e80a922656b830 to your computer and use it in GitHub Desktop.
Save chrisveness/f3f865e80a922656b830 to your computer and use it in GitHub Desktop.
Encrypt/decrypt object to be stored secure from prying eyes
<?php
/**
* Encrypts object to be stored secure from prying eyes (uses AES-256 ECB).
*
* @param object $sourceObj Object to be encrypted.
* @param string $key Key to use for encryption.
* @return string Encrypted object.
*/
function objEncrypt($sourceObj, $key)
{
$sourceJson = json_encode($sourceObj, JSON_FORCE_OBJECT);
$ciphertext = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, sha1($key,true), $sourceJson, MCRYPT_MODE_ECB));
return $ciphertext;
}
/**
* Decrypts encrypted object.
*
* @param $cipherObj Encrypted object.
* @param string $key Key used for encryption.
* @return object Original object.
*/
function objDecrypt($cipherObj, $key)
{
$sourceJson = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, sha1($key,true), base64_decode($cipherObj), MCRYPT_MODE_ECB);
$obj = json_decode(rtrim($sourceJson, "\0"));
return $obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment