Highway to PSR2
[openemr.git] / portal / patient / fwk / libs / verysimple / Encryption / McryptUtil.php
blobfaa69cb4852f2fa8b3b01fc90c9d5667d894035f
1 <?php
2 /** @package verysimple::Encryption */
4 /**
5 * require supporting files
6 */
8 /**
9 * A static utility class for encryption/decrytion using the php mcrypt functionality
11 * @package verysimple::Encryption::McryptUtil
13 class McryptUtil
15 static $IV;
16 static $CIPHER = MCRYPT_RIJNDAEL_256;
17 static $MODE = MCRYPT_MODE_ECB;
19 /**
20 * Creates the initialization vector.
21 * This method is called automatically
22 * when encrypt/decrypt are called and does not need to be explicitly called
24 static function Init()
26 if (! McryptUtil::$IV) {
27 if (! function_exists("mcrypt_get_iv_size")) {
28 throw new Exception("The mcrypt extension does not appear to be enabled.");
31 $iv_size = mcrypt_get_iv_size(McryptUtil::$CIPHER, McryptUtil::$MODE);
32 McryptUtil::$IV = mcrypt_create_iv($iv_size, MCRYPT_RAND);
36 /**
37 * Encrypts data
39 * @param
40 * string data to be encrypted
41 * @param
42 * string encryption key/passphrase
43 * @param
44 * bool [optional] true to base64 encode the result
45 * @return string encrypted data
47 static function Encrypt($data, $key, $encode = true)
49 McryptUtil::Init();
51 $encrypted = mcrypt_encrypt(McryptUtil::$CIPHER, $key, $data, McryptUtil::$MODE, McryptUtil::$IV);
53 return ($encode) ? base64_encode($encrypted) : $encrypted;
56 /**
57 * Decrypts data that was previously encrypted
59 * @param
60 * string data to be decrypted
61 * @param
62 * string encryption key/passphrase
63 * @param
64 * bool [optional] true if the encrypted string is base64 encoded
65 * @param
66 * bool [optional] true to strip the null character padding at the end
67 * @return string decrypted data
69 static function Decrypt($data, $key, $decode = true, $strip_nulls = true)
71 McryptUtil::Init();
73 if ($decode) {
74 $data = base64_decode($data);
77 $decrypted = mcrypt_decrypt(McryptUtil::$CIPHER, $key, $data, McryptUtil::$MODE, McryptUtil::$IV);
79 // mcrypt pads the end of the block with null chars, so we need to strip them
80 return $strip_nulls ? rtrim($decrypted, "\0") : $decrypted;