Created
June 17, 2014 12:30
-
-
Save chrisveness/f3f865e80a922656b830 to your computer and use it in GitHub Desktop.
Encrypt/decrypt object to be stored secure from prying eyes
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 | |
/** | |
* 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