3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Utils_Crypt
{
20 * Encrypts a string using AES256 in ECB mode, if encryption is enabled.
22 * After encrypting the string, it is base64 encoded.
24 * If encryption is not enabled, either due to CIVICRM_SITE_KEY being
25 * undefined or due to unavailability of the mcrypt module, the string is
26 * merely base64 encoded and is not encrypted at all.
28 * @param string $string
29 * Plaintext to be encrypted.
31 * Base64-encoded ciphertext, or base64-encoded plaintext if encryption is
32 * disabled or unavailable.
34 public static function encrypt($string) {
39 if (function_exists('mcrypt_module_open') &&
40 defined('CIVICRM_SITE_KEY')
43 $td = mcrypt_module_open(MCRYPT_RIJNDAEL_256
, '', MCRYPT_MODE_ECB
, '');
44 // ECB mode - iv not needed - CRM-8198
45 $iv = '00000000000000000000000000000000';
46 $ks = mcrypt_enc_get_key_size($td);
47 $key = substr(sha1(CIVICRM_SITE_KEY
), 0, $ks);
49 mcrypt_generic_init($td, $key, $iv);
50 $string = mcrypt_generic($td, $string);
51 mcrypt_generic_deinit($td);
52 mcrypt_module_close($td);
55 return base64_encode($string);
59 * Decrypts ciphertext encrypted with AES256 in ECB mode, if possible.
61 * If the mcrypt module is not available or if CIVICRM_SITE_KEY is not set,
62 * the provided ciphertext is only base64-decoded, not decrypted.
64 * @param string $string
65 * Ciphertext to be decrypted.
67 * Plaintext, or base64-decoded ciphertext if encryption is disabled or
70 public static function decrypt($string) {
75 $string = base64_decode($string);
80 if (function_exists('mcrypt_module_open') &&
81 defined('CIVICRM_SITE_KEY')
84 $td = mcrypt_module_open(MCRYPT_RIJNDAEL_256
, '', MCRYPT_MODE_ECB
, '');
85 // ECB mode - iv not needed - CRM-8198
86 $iv = '00000000000000000000000000000000';
87 $ks = mcrypt_enc_get_key_size($td);
88 $key = substr(sha1(CIVICRM_SITE_KEY
), 0, $ks);
90 mcrypt_generic_init($td, $key, $iv);
91 $string = rtrim(mdecrypt_generic($td, $string));
92 mcrypt_generic_deinit($td);
93 mcrypt_module_close($td);