Search code examples
phpmcrypt

Using defined security variables inside a function


I found out that I should not use global variables like global $auth_key for sensitive data's (Correct me if that's not true.) so I wanted to use defined variables for storing security keys.

Inside config.php salt keys are defined.

define('AUTH_KEY','::~K~UC*[tlu4Eq/]Lm|h');

define('SECURE_AUTH_KEY', 'QsTMvbV+tuU{K26!]J2');

In encryption.php contains the encryption functions where AUTH_KEY and SECURE_AUTH_KEY will be used inside.

function encrypt_text($value) {
   if(!$value) return false;
   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, **AUTH_KEY_HERE**, $value, MCRYPT_MODE_ECB, **SECURE_AUTH_KEY_HERE**);
   return trim(base64_encode($crypttext));
}

function decrypt_text($value) {
   if(!$value) return false;
   $crypttext = base64_decode($value);
   $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, **AUTH_KEY_HERE**, $crypttext, MCRYPT_MODE_ECB, **SECURE_AUTH_KEY_HERE**);
   return trim($decrypttext);
}

Is there a way to do that? or any other solutions you can recommend? Please note that these keys are real important for encryption of sensitive informations.

Also, a another question, what is the maximum length of keys to be used on mcrypt?

Thank you and looking forward for reply of yours.


Solution

  • Using a constant is just like using a variable except there is no dollar sign.

    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, AUTH_KEY, $value, MCRYPT_MODE_ECB, SECURE_AUTH);
    

    There is nothing inherently more secure in this approach over using the global key word. Though this approach is preferred. By using a constant you are saying this is a static value I will use across the application. Having to use global on the other hand is often just a result of bad design or laziness. It leads to code that is hard to follow, abusing what scoping tries to accomplish.

    Key length is dependent on the encryption algorithm used. RTM.