Go to the documentation of this file.00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00015 final class Crypter
00016 {
00017 private $crResource = null;
00018 private $keySize = null;
00019 private $iv = null;
00020
00021 public static function create($algorithm, $mode)
00022 {
00023 return new self($algorithm, $mode);
00024 }
00025
00026 public function __construct($algorithm, $mode)
00027 {
00028 if (
00029 !$this->crResource
00030 = mcrypt_module_open($algorithm, null, $mode, null)
00031 )
00032 throw new WrongStateException('Mcrypt Module did not open.');
00033
00034 $this->iv = mcrypt_create_iv(
00035 mcrypt_enc_get_iv_size($this->crResource),
00036 MCRYPT_DEV_URANDOM
00037 );
00038
00039 $this->keySize = mcrypt_enc_get_key_size($this->crResource);
00040 }
00041
00042 public function __destruct()
00043 {
00044 mcrypt_generic_deinit($this->crResource);
00045 mcrypt_module_close($this->crResource);
00046 }
00047
00048 public function encrypt($secret, $data)
00049 {
00050 mcrypt_generic_init(
00051 $this->crResource,
00052 $this->createKey($secret),
00053 $this->iv
00054 );
00055
00056 return mcrypt_generic($this->crResource, $data);
00057 }
00058
00059 public function decrypt($secret, $encryptedData)
00060 {
00061 mcrypt_generic_init(
00062 $this->crResource,
00063 $this->createKey($secret),
00064 $this->iv
00065 );
00066
00067
00068 return rtrim(
00069 mdecrypt_generic($this->crResource, $encryptedData),
00070 "\0"
00071 );
00072 }
00073
00074 private function createKey($secret)
00075 {
00076 return substr(md5($secret), 0, $this->keySize);
00077 }
00078 }
00079 ?>