Versions
Look up a class, method, property or event

CSecurityManager

Package system.base
Inheritance class CSecurityManager » CApplicationComponent » CComponent
Implements IApplicationComponent
Since 1.0
Source Code framework/base/CSecurityManager.php
CSecurityManager provides private keys, hashing and encryption functions.

CSecurityManager is used by Yii components and applications for security-related purpose. For example, it is used in cookie validation feature to prevent cookie data from being tampered.

CSecurityManager is mainly used to protect data from being tampered and viewed. It can generate HMAC and encrypt the data. The private key used to generate HMAC is set by ValidationKey. The key used to encrypt data is specified by EncryptionKey. If the above keys are not explicitly set, random keys will be generated and used.

To protected data with HMAC, call hashData(); and to check if the data is tampered, call validateData(), which will return the real data if it is not tampered. The algorithm used to generated HMAC is specified by validation.

To encrypt and decrypt data, call encrypt() and decrypt() respectively, which uses 3DES encryption algorithm. Note, the PHP Mcrypt extension must be installed and loaded.

CSecurityManager is a core application component that can be accessed via CApplication::getSecurityManager().

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
behaviors array the behaviors that should be attached to this component. CApplicationComponent
cryptAlgorithm mixed the name of the crypt algorithm to be used by encrypt and decrypt. CSecurityManager
encryptionKey string the private key used to encrypt/decrypt data. CSecurityManager
hashAlgorithm string the name of the hashing algorithm to be used by computeHMAC. CSecurityManager
isInitialized boolean Checks if this application component has been initialized. CApplicationComponent
validation string This method has been deprecated since version 1.1.3. CSecurityManager
validationKey string the private key used to generate HMAC. CSecurityManager

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
computeHMAC() Computes the HMAC for the data with validationKey. This method has been made public CSecurityManager
decrypt() Decrypts data CSecurityManager
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
encrypt() Encrypts data. CSecurityManager
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
generatePseudoRandomBlock() Generate a pseudo random block of data using several sources. On some systems this may be a bit CSecurityManager
generateRandomBytes() Generates a string of random bytes. CSecurityManager
generateRandomString() Generate a random ASCII string. Generates only [0-9a-zA-z_~] characters which are all CSecurityManager
generateSessionRandomBlock() Get random bytes from the system entropy source via PHP session manager. CSecurityManager
getEncryptionKey() Returns the private key used to encrypt/decrypt data. If the key is not explicitly set, a random one is generated and returned. CSecurityManager
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getIsInitialized() Checks if this application component has been initialized. CApplicationComponent
getValidation() This method has been deprecated since version 1.1.3. CSecurityManager
getValidationKey() Returns the private key used to generate HMAC. If the key is not explicitly set, a random one is generated and returned. CSecurityManager
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
hashData() Prefixes data with an HMAC. CSecurityManager
init() CSecurityManager
raiseEvent() Raises an event. CComponent
setEncryptionKey() Sets the key used to encrypt/decrypt data. CSecurityManager
setValidation() This method has been deprecated since version 1.1.3. CSecurityManager
setValidationKey() Sets the key used to generate HMAC CSecurityManager
validateData() Validates if data is tampered. CSecurityManager

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
generateRandomKey() CSecurityManager
openCryptModule() Opens the mcrypt module with the configuration specified in cryptAlgorithm. CSecurityManager

Property Details

cryptAlgorithm property (available since v1.1.3)
public mixed $cryptAlgorithm;

the name of the crypt algorithm to be used by encrypt and decrypt. This will be passed as the first parameter to mcrypt_module_open.

This property can also be configured as an array. In this case, the array elements will be passed in order as parameters to mcrypt_module_open. For example, array('rijndael-256', '', 'ofb', '').

Defaults to 'des', meaning using DES crypt algorithm.

encryptionKey property
public string getEncryptionKey()
public void setEncryptionKey(string $value)

the private key used to encrypt/decrypt data. If the key is not explicitly set, a random one is generated and returned.

hashAlgorithm property (available since v1.1.3)
public string $hashAlgorithm;

the name of the hashing algorithm to be used by computeHMAC. See hash-algos for the list of possible hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'.

Defaults to 'sha1', meaning using SHA1 hash algorithm.

validation property
public string getValidation()
public void setValidation(string $value)

This method has been deprecated since version 1.1.3. Please use hashAlgorithm instead.

validationKey property
public string getValidationKey()
public void setValidationKey(string $value)

the private key used to generate HMAC. If the key is not explicitly set, a random one is generated and returned.

Method Details

computeHMAC() method
public string computeHMAC(string $data, string|null $key=NULL, string|null $hashAlgorithm=NULL)
$data string data to be generated HMAC.
$key string|null the private key to be used for generating HMAC. Defaults to null, meaning using validationKey value.
$hashAlgorithm string|null the name of the hashing algorithm to be used. See hash-algos for the list of possible hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'. Defaults to null, meaning using hashAlgorithm value.
{return} string the HMAC for the data.
Source Code: framework/base/CSecurityManager.php#298 (show)
public function computeHMAC($data,$key=null,$hashAlgorithm=null)
{
    if(
$key===null)
        
$key=$this->getValidationKey();
    if(
$hashAlgorithm===null)
        
$hashAlgorithm=$this->hashAlgorithm;

    if(
function_exists('hash_hmac'))
        return 
hash_hmac($hashAlgorithm,$data,$key);

    if(
0===strcasecmp($hashAlgorithm,'sha1'))
    {
        
$pack='H40';
        
$func='sha1';
    }
    elseif(
0===strcasecmp($hashAlgorithm,'md5'))
    {
        
$pack='H32';
        
$func='md5';
    }
    else
    {
        throw new 
CException(Yii::t('yii','Only SHA1 and MD5 hashing algorithms are supported when using PHP 5.1.1 or below.'));
    }
    if(
$this->strlen($key)>64)
        
$key=pack($pack,$func($key));
    if(
$this->strlen($key)<64)
        
$key=str_pad($key,64,chr(0));
    
$key=$this->substr($key,0,64);
    return 
$func((str_repeat(chr(0x5C), 64) ^ $key) . pack($pack$func((str_repeat(chr(0x36), 64) ^ $key) . $data)));
}

Computes the HMAC for the data with validationKey. This method has been made public since 1.1.14.

decrypt() method
public string decrypt(string $data, string $key=NULL)
$data string data to be decrypted.
$key string the decryption key. This defaults to null, meaning using EncryptionKey.
{return} string the decrypted data
Source Code: framework/base/CSecurityManager.php#216 (show)
public function decrypt($data,$key=null)
{
    
$module=$this->openCryptModule();
    
$key=$this->substr($key===null md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
    
$ivSize=mcrypt_enc_get_iv_size($module);
    
$iv=$this->substr($data,0,$ivSize);
    
mcrypt_generic_init($module,$key,$iv);
    
$decrypted=mdecrypt_generic($module,$this->substr($data,$ivSize,$this->strlen($data)));
    
mcrypt_generic_deinit($module);
    
mcrypt_module_close($module);
    return 
rtrim($decrypted,"\0");
}

Decrypts data

encrypt() method
public string encrypt(string $data, string $key=NULL)
$data string data to be encrypted.
$key string the decryption key. This defaults to null, meaning using EncryptionKey.
{return} string the encrypted data
Source Code: framework/base/CSecurityManager.php#196 (show)
public function encrypt($data,$key=null)
{
    
$module=$this->openCryptModule();
    
$key=$this->substr($key===null md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
    
srand();
    
$iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
    
mcrypt_generic_init($module,$key,$iv);
    
$encrypted=$iv.mcrypt_generic($module,$data);
    
mcrypt_generic_deinit($module);
    
mcrypt_module_close($module);
    return 
$encrypted;
}

Encrypts data.

generatePseudoRandomBlock() method (available since v1.1.14)
public string generatePseudoRandomBlock()
{return} string of 64 pseudo random bytes.
Source Code: framework/base/CSecurityManager.php#411 (show)
public function generatePseudoRandomBlock()
{
    
$bytes='';

    if (
function_exists('openssl_random_pseudo_bytes')
        && (
$bytes=openssl_random_pseudo_bytes(512))!==false
        
&& $this->strlen($bytes)>=512)
    {
        return 
$this->substr($bytes,0,512);
    }

    for(
$i=0;$i<32;++$i)
        
$bytes.=pack('S',mt_rand(0,0xffff));

    
// On UNIX and UNIX-like operating systems the numerical values in `ps`, `uptime` and `iostat`
    // ought to be fairly unpredictable. Gather the non-zero digits from those.
    
foreach(array('ps','uptime','iostat') as $command) {
        @
exec($command,$commandResult,$retVal);
        if(
is_array($commandResult) && !empty($commandResult) && $retVal==0)
            
$bytes.=preg_replace('/[^1-9]/','',implode('',$commandResult));
    }

    
// Gather the current time's microsecond part. Note: this is only a source of entropy on
    // the first call! If multiple calls are made, the entropy is only as much as the
    // randomness in the time between calls.
    
$bytes.=$this->substr(microtime(),2,6);

    
// Concatenate everything gathered, mix it with sha512. hash() is part of PHP core and
    // enabled by default but it can be disabled at compile time but we ignore that possibility here.
    
return hash('sha512',$bytes,true);
}

Generate a pseudo random block of data using several sources. On some systems this may be a bit better than PHP's mt_rand built-in function, which is not really random.

generateRandomBytes() method (available since v1.1.14)
public boolean|string generateRandomBytes(integer $length, boolean $cryptographicallyStrong=true)
$length integer number of random bytes to be generated.
$cryptographicallyStrong boolean whether to fail if a cryptographically strong result cannot be generated. The method attempts to read from a cryptographically strong pseudorandom number generator (CS-PRNG), see Wikipedia. However, in some runtime environments, PHP has no access to a CS-PRNG, in which case the method returns false if $cryptographicallyStrong is true. When $cryptographicallyStrong is false, the method always returns a pseudorandom result but may fall back to using generatePseudoRandomBlock. This method does not guarantee that entropy, from sources external to the CS-PRNG, was mixed into the CS-PRNG state between each successive call. The caller can therefore expect non-blocking behavior, unlike, for example, reading from /dev/random on Linux, see Gutterman et al 2006.
{return} boolean|string generated random binary string or false on failure.
Source Code: framework/base/CSecurityManager.php#362 (show)
public function generateRandomBytes($length,$cryptographicallyStrong=true)
{
    
$bytes='';
    if(
function_exists('openssl_random_pseudo_bytes'))
    {
        
$bytes=openssl_random_pseudo_bytes($length,$strong);
        if(
$this->strlen($bytes)>=$length && ($strong || !$cryptographicallyStrong))
            return 
$this->substr($bytes,0,$length);
    }

    if(
function_exists('mcrypt_create_iv') &&
        (
$bytes=mcrypt_create_iv($lengthMCRYPT_DEV_URANDOM))!==false &&
        
$this->strlen($bytes)>=$length)
    {
        return 
$this->substr($bytes,0,$length);
    }

    if((
$file=@fopen('/dev/urandom','rb'))!==false &&
        (
$bytes=@fread($file,$length))!==false &&
        (
fclose($file) || true) &&
        
$this->strlen($bytes)>=$length)
    {
        return 
$this->substr($bytes,0,$length);
    }

    
$i=0;
    while(
$this->strlen($bytes)<$length &&
        (
$byte=$this->generateSessionRandomBlock())!==false &&
        ++
$i<3)
    {
        
$bytes.=$byte;
    }
    if(
$this->strlen($bytes)>=$length)
        return 
$this->substr($bytes,0,$length);

    if (
$cryptographicallyStrong)
        return 
false;

    while(
$this->strlen($bytes)<$length)
        
$bytes.=$this->generatePseudoRandomBlock();
    return 
$this->substr($bytes,0,$length);
}

Generates a string of random bytes.

generateRandomKey() method
protected string generateRandomKey()
{return} string a randomly generated private key.
Source Code: framework/base/CSecurityManager.php#86 (show)
protected function generateRandomKey()
{
    return 
$this->generateRandomString(32);
}

generateRandomString() method (available since v1.1.14)
public string|boolean generateRandomString(integer $length, boolean $cryptographicallyStrong=true)
$length integer length of the generated string in characters.
$cryptographicallyStrong boolean set this to require cryptographically strong randomness.
{return} string|boolean random string or false in case it cannot be generated.
Source Code: framework/base/CSecurityManager.php#338 (show)
public function generateRandomString($length,$cryptographicallyStrong=true)
{
    if((
$randomBytes=$this->generateRandomBytes($length+2,$cryptographicallyStrong))!==false)
        return 
strtr($this->substr(base64_encode($randomBytes),0,$length),array('+'=>'_','/'=>'~'));
    return 
false;
}

Generate a random ASCII string. Generates only [0-9a-zA-z_~] characters which are all transparent in raw URL encoding.

generateSessionRandomBlock() method (available since v1.1.14)
public boolean|string generateSessionRandomBlock()
{return} boolean|string 20-byte random binary string or false on error.
Source Code: framework/base/CSecurityManager.php#448 (show)
public function generateSessionRandomBlock()
{
    
ini_set('session.entropy_length',20);
    if(
ini_get('session.entropy_length')!=20)
        return 
false;

    
// These calls are (supposed to be, according to PHP manual) safe even if
    // there is already an active session for the calling script.
    
@session_start();
    @
session_regenerate_id();

    
$bytes=session_id();
    if(!
$bytes)
        return 
false;

    
// $bytes has 20 bytes of entropy but the session manager converts the binary
    // random bytes into something readable. We have to convert that back.
    // SHA-1 should do it without losing entropy.
    
return sha1($bytes,true);
}

Get random bytes from the system entropy source via PHP session manager.

getEncryptionKey() method
public string getEncryptionKey()
{return} string the private key used to encrypt/decrypt data. If the key is not explicitly set, a random one is generated and returned.
Source Code: framework/base/CSecurityManager.php#134 (show)
public function getEncryptionKey()
{
    if(
$this->_encryptionKey!==null)
        return 
$this->_encryptionKey;
    else
    {
        if((
$key=Yii::app()->getGlobalState(self::STATE_ENCRYPTION_KEY))!==null)
            
$this->setEncryptionKey($key);
        else
        {
            if((
$key=$this->generateRandomString(32,true))===false)
                if((
$key=$this->generateRandomString(32,false))===false)
                    throw new 
CException(Yii::t('yii',
                        
'CSecurityManager::generateRandomString() cannot generate random string in the current environment.'));
            
$this->setEncryptionKey($key);
            
Yii::app()->setGlobalState(self::STATE_ENCRYPTION_KEY,$key);
        }
        return 
$this->_encryptionKey;
    }
}

getValidation() method
public string getValidation()
{return} string -
Source Code: framework/base/CSecurityManager.php#173 (show)
public function getValidation()
{
    return 
$this->hashAlgorithm;
}

This method has been deprecated since version 1.1.3. Please use hashAlgorithm instead.

getValidationKey() method
public string getValidationKey()
{return} string the private key used to generate HMAC. If the key is not explicitly set, a random one is generated and returned.
Source Code: framework/base/CSecurityManager.php#96 (show)
public function getValidationKey()
{
    if(
$this->_validationKey!==null)
        return 
$this->_validationKey;
    else
    {
        if((
$key=Yii::app()->getGlobalState(self::STATE_VALIDATION_KEY))!==null)
            
$this->setValidationKey($key);
        else
        {
            if((
$key=$this->generateRandomString(32,true))===false)
                if((
$key=$this->generateRandomString(32,false))===false)
                    throw new 
CException(Yii::t('yii',
                        
'CSecurityManager::generateRandomString() cannot generate random string in the current environment.'));
            
$this->setValidationKey($key);
            
Yii::app()->setGlobalState(self::STATE_VALIDATION_KEY,$key);
        }
        return 
$this->_validationKey;
    }
}

hashData() method
public string hashData(string $data, string $key=NULL)
$data string data to be hashed.
$key string the private key to be used for generating HMAC. Defaults to null, meaning using validationKey.
{return} string data prefixed with HMAC
Source Code: framework/base/CSecurityManager.php#259 (show)
public function hashData($data,$key=null)
{
    return 
$this->computeHMAC($data,$key).$data;
}

Prefixes data with an HMAC.

init() method
public void init()
Source Code: framework/base/CSecurityManager.php#76 (show)
public function init()
{
    
parent::init();
    
$this->_mbstring=extension_loaded('mbstring');
}

openCryptModule() method (available since v1.1.3)
protected resource openCryptModule()
{return} resource the mycrypt module handle.
Source Code: framework/base/CSecurityManager.php#235 (show)
protected function openCryptModule()
{
    if(
extension_loaded('mcrypt'))
    {
        if(
is_array($this->cryptAlgorithm))
            
$module=@call_user_func_array('mcrypt_module_open',$this->cryptAlgorithm);
        else
            
$module=@mcrypt_module_open($this->cryptAlgorithm,''MCRYPT_MODE_CBC,'');

        if(
$module===false)
            throw new 
CException(Yii::t('yii','Failed to initialize the mcrypt module.'));

        return 
$module;
    }
    else
        throw new 
CException(Yii::t('yii','CSecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
}

Opens the mcrypt module with the configuration specified in cryptAlgorithm.

setEncryptionKey() method
public void setEncryptionKey(string $value)
$value string the key used to encrypt/decrypt data.
Source Code: framework/base/CSecurityManager.php#159 (show)
public function setEncryptionKey($value)
{
    if(!empty(
$value))
        
$this->_encryptionKey=$value;
    else
        throw new 
CException(Yii::t('yii','CSecurityManager.encryptionKey cannot be empty.'));
}

setValidation() method
public void setValidation(string $value)
$value string -
Source Code: framework/base/CSecurityManager.php#184 (show)
public function setValidation($value)
{
    
$this->hashAlgorithm=$value;
}

This method has been deprecated since version 1.1.3. Please use hashAlgorithm instead.

setValidationKey() method
public void setValidationKey(string $value)
$value string the key used to generate HMAC
Source Code: framework/base/CSecurityManager.php#121 (show)
public function setValidationKey($value)
{
    if(!empty(
$value))
        
$this->_validationKey=$value;
    else
        throw new 
CException(Yii::t('yii','CSecurityManager.validationKey cannot be empty.'));
}

validateData() method
public string validateData(string $data, string $key=NULL)
$data string data to be validated. The data must be previously generated using hashData().
$key string the private key to be used for generating HMAC. Defaults to null, meaning using validationKey.
{return} string the real data with HMAC stripped off. False if the data is tampered.
Source Code: framework/base/CSecurityManager.php#272 (show)
public function validateData($data,$key=null)
{
    
$len=$this->strlen($this->computeHMAC('test'));
    if(
$this->strlen($data)>=$len)
    {
        
$hmac=$this->substr($data,0,$len);
        
$data2=$this->substr($data,$len,$this->strlen($data));
        return 
$hmac===$this->computeHMAC($data2,$key)?$data2:false;
    }
    else
        return 
false;
}

Validates if data is tampered.

Be the first person to leave a comment

Please to leave your comment.