Last active
August 29, 2015 14:26
-
-
Save LarsNieuwenhuizen/ea6464e52b528a0f9ba1 to your computer and use it in GitHub Desktop.
Simple service class to encrypt and decrypt string using php5-mcrypt
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 | |
namespace Package\Key\Service; | |
use TYPO3\Flow\Annotations as Flow; | |
/** | |
* Class EncryptionService | |
* | |
* @Flow\Scope("singleton") | |
*/ | |
class EncryptionService { | |
/** | |
* @Flow\Inject(setting="Package.Key.encryption.privateKey", package="Package.Key") | |
* @var string | |
*/ | |
protected $privateKey; | |
/** | |
* @param $string | |
* @return string | |
*/ | |
public function encryptString($string) { | |
$key = $this->privateKey; | |
$string = str_pad($string, 1, ' ', STR_PAD_BOTH); | |
$iv = mcrypt_create_iv( | |
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), | |
MCRYPT_DEV_URANDOM | |
); | |
$encrypted = base64_encode( | |
$iv . | |
mcrypt_encrypt( | |
MCRYPT_RIJNDAEL_256, | |
hash('sha256', $key, true), | |
$string, | |
MCRYPT_MODE_CBC, | |
$iv | |
) | |
); | |
return $encrypted; | |
} | |
/** | |
* @param $string | |
* @return string | |
*/ | |
public function decryptString($string) { | |
$key = $this->privateKey; | |
$encrypted = $string; | |
$data = base64_decode($encrypted); | |
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)); | |
$decrypted = rtrim( | |
mcrypt_decrypt( | |
MCRYPT_RIJNDAEL_256, | |
hash('sha256', $key, true), | |
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)), | |
MCRYPT_MODE_CBC, | |
$iv | |
), | |
"\0" | |
); | |
return trim($decrypted); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment