Class yii\base\Security

Inheritanceyii\base\Security » yii\base\Component » yii\base\Object
Implementsyii\base\Configurable
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/base/Security.php

Security provides a set of methods to handle common security-related tasks.

In particular, Security supports the following features:

Note: this class requires 'OpenSSL' PHP extension for random key/string generation on Windows and for encryption/decryption on all platforms. For the highest security level PHP version >= 5.5.0 is recommended.

For more details and usage information on Security, see the guide article on security.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$allowedCiphers array[] Look-up table of block sizes and key sizes for each supported OpenSSL cipher. yii\base\Security
$authKeyInfo string HKDF info value for derivation of message authentication key. yii\base\Security
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$cipher string The cipher to use for encryption and decryption. yii\base\Security
$derivationIterations integer Derivation iterations count. yii\base\Security
$kdfHash string Hash algorithm for key derivation. yii\base\Security
$macHash string Hash algorithm for message authentication. yii\base\Security
$passwordHashCost integer Default cost used for password hashing. yii\base\Security
$passwordHashStrategy string Strategy, which should be used to generate password hash. yii\base\Security

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\Object
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\Object
compareString() Performs string comparison using timing attack resistant approach. yii\base\Security
decryptByKey() Verifies and decrypts data encrypted with encryptByKey(). yii\base\Security
decryptByPassword() Verifies and decrypts data encrypted with encryptByPassword(). yii\base\Security
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
encryptByKey() Encrypts data using a cryptographic key. yii\base\Security
encryptByPassword() Encrypts data using a password. yii\base\Security
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
generatePasswordHash() Generates a secure hash from a password and a random salt. yii\base\Security
generateRandomKey() Generates specified number of random bytes. yii\base\Security
generateRandomString() Generates a random string of specified length. yii\base\Security
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
hashData() Prefixes data with a keyed hash value so that it can later be detected if it is tampered. yii\base\Security
hkdf() Derives a key from the given input key using the standard HKDF algorithm. yii\base\Security
init() Initializes the object. yii\base\Object
maskToken() Masks a token to make it uncompressible. yii\base\Security
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
pbkdf2() Derives a key from the given password using the standard PBKDF2 algorithm. yii\base\Security
trigger() Triggers an event. yii\base\Component
unmaskToken() Unmasks a token previously masked by maskToken. yii\base\Security
validateData() Validates if the given data is tampered. yii\base\Security
validatePassword() Verifies a password against a hash. yii\base\Security

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
decrypt() Decrypts data. yii\base\Security
encrypt() Encrypts data. yii\base\Security
generateSalt() Generates a salt that can be used to generate a password hash. yii\base\Security

Property Details

$allowedCiphers public property

Look-up table of block sizes and key sizes for each supported OpenSSL cipher.

In each element, the key is one of the ciphers supported by OpenSSL (@see openssl_get_cipher_methods()). The value is an array of two integers, the first is the cipher's block size in bytes and the second is the key size in bytes.

Warning: All OpenSSL ciphers that we recommend are in the default value, i.e. AES in CBC mode.

Note: Yii's encryption protocol uses the same size for cipher key, HMAC signature key and key derivation salt.

public array[] $allowedCiphers = ['AES-128-CBC' => [1616], 'AES-192-CBC' => [1624], 'AES-256-CBC' => [1632]]
$authKeyInfo public property

HKDF info value for derivation of message authentication key.

See also hkdf().

public string $authKeyInfo 'AuthorizationKey'
$cipher public property

The cipher to use for encryption and decryption.

public string $cipher 'AES-128-CBC'
$derivationIterations public property

Derivation iterations count. Set as high as possible to hinder dictionary password attacks.

$kdfHash public property

Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.

See also hash_algos().

public string $kdfHash 'sha256'
$macHash public property

Hash algorithm for message authentication. Recommend sha256, sha384 or sha512.

See also hash_algos().

public string $macHash 'sha256'
$passwordHashCost public property (available since version 2.0.6)

Default cost used for password hashing. Allowed value is between 4 and 31.

See also generatePasswordHash().

$passwordHashStrategy public property
Deprecated since version 2.0.7, generatePasswordHash() ignores $passwordHashStrategy and uses password_hash() when available or crypt() when not.

Strategy, which should be used to generate password hash. Available strategies:

  • 'password_hash' - use of PHP password_hash() function with PASSWORD_DEFAULT algorithm. This option is recommended, but it requires PHP version >= 5.5.0
  • 'crypt' - use PHP crypt() function.

Method Details

compareString() public method

Performs string comparison using timing attack resistant approach.

See also http://codereview.stackexchange.com/questions/13512.

public boolean compareString ( $expected, $actual )
$expected string

String to compare.

$actual string

User-supplied string.

return boolean

Whether strings are equal.

decrypt() protected method

Decrypts data.

See also encrypt().

protected boolean|string decrypt ( $data, $passwordBased, $secret, $info )
$data string

Encrypted data to be decrypted.

$passwordBased boolean

Set true to use password-based key derivation

$secret string

The decryption password or key

$info string|null

Context/application specific information, @see encrypt()

return boolean|string

The decrypted data or false on authentication failure

throws yii\base\InvalidConfigException

on OpenSSL not loaded

throws yii\base\Exception

on OpenSSL error

decryptByKey() public method

Verifies and decrypts data encrypted with encryptByKey().

See also encryptByKey().

public boolean|string decryptByKey ( $data, $inputKey, $info null )
$data string

The encrypted data to decrypt

$inputKey string

The input to use for encryption and authentication

$info string

Optional context and application specific information, see hkdf()

return boolean|string

The decrypted data or false on authentication failure

decryptByPassword() public method

Verifies and decrypts data encrypted with encryptByPassword().

See also encryptByPassword().

public boolean|string decryptByPassword ( $data, $password )
$data string

The encrypted data to decrypt

$password string

The password to use for decryption

return boolean|string

The decrypted data or false on authentication failure

encrypt() protected method

Encrypts data.

See also decrypt().

protected string encrypt ( $data, $passwordBased, $secret, $info )
$data string

Data to be encrypted

$passwordBased boolean

Set true to use password-based key derivation

$secret string

The encryption password or key

$info string|null

Context/application specific information, e.g. a user ID See RFC 5869 Section 3.2 for more details.

return string

The encrypted data

throws yii\base\InvalidConfigException

on OpenSSL not loaded

throws yii\base\Exception

on OpenSSL error

encryptByKey() public method

Encrypts data using a cryptographic key.

Derives keys for encryption and authentication from the input key using HKDF and a random salt, which is very fast relative to encryptByPassword(). The input key must be properly random -- use generateRandomKey() to generate keys. The encrypted data includes a keyed message authentication code (MAC) so there is no need to hash input or output data.

See also:

public string encryptByKey ( $data, $inputKey, $info null )
$data string

The data to encrypt

$inputKey string

The input to use for encryption and authentication

$info string

Optional context and application specific information, see hkdf()

return string

The encrypted data

encryptByPassword() public method

Encrypts data using a password.

Derives keys for encryption and authentication from the password using PBKDF2 and a random salt, which is deliberately slow to protect against dictionary attacks. Use encryptByKey() to encrypt fast using a cryptographic key rather than a password. Key derivation time is determined by $derivationIterations, which should be set as high as possible. The encrypted data includes a keyed message authentication code (MAC) so there is no need to hash input or output data. > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against poor-quality or compromised passwords.

See also:

public string encryptByPassword ( $data, $password )
$data string

The data to encrypt

$password string

The password to use for encryption

return string

The encrypted data

generatePasswordHash() public method

Generates a secure hash from a password and a random salt.

The generated hash can be stored in database. Later when a password needs to be validated, the hash can be fetched and passed to validatePassword(). For example,

// generates the hash (usually done during user registration or when the password is changed)
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
// ...save $hash in database...

// during login, validate if the password entered is correct using $hash fetched from database
if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
    // password is good
} else {
    // password is bad
}

See also validatePassword().

public string generatePasswordHash ( $password, $cost null )
$password string

The password to be hashed.

$cost integer

Cost parameter used by the Blowfish hash algorithm. The higher the value of cost, the longer it takes to generate the hash and to verify a password against it. Higher cost therefore slows down a brute-force attack. For best protection against brute-force attacks, set it to the highest value that is tolerable on production servers. The time taken to compute the hash doubles for every increment by one of $cost.

return string

The password hash string. When $passwordHashStrategy is set to 'crypt', the output is always 60 ASCII characters, when set to 'password_hash' the output length might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)

throws yii\base\Exception

on bad password parameter or cost parameter.

generateRandomKey() public method

Generates specified number of random bytes.

Note that output may not be ASCII.

See also generateRandomString() if you need a string.

public string generateRandomKey ( $length 32 )
$length integer

The number of bytes to generate

return string

The generated random bytes

throws yii\base\InvalidParamException

if wrong length is specified

throws yii\base\Exception

on failure.

generateRandomString() public method

Generates a random string of specified length.

The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.

public string generateRandomString ( $length 32 )
$length integer

The length of the key in characters

return string

The generated random key

throws yii\base\Exception

on failure.

generateSalt() protected method

Generates a salt that can be used to generate a password hash.

The PHP crypt() built-in function requires, for the Blowfish hash algorithm, a salt string in a specific format: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z".

protected string generateSalt ( $cost 13 )
$cost integer

The cost parameter

return string

The random salt value.

throws yii\base\InvalidParamException

if the cost parameter is out of the range of 4 to 31.

hashData() public method

Prefixes data with a keyed hash value so that it can later be detected if it is tampered.

There is no need to hash inputs or outputs of encryptByKey() or encryptByPassword() as those methods perform the task.

See also:

public string hashData ( $data, $key, $rawHash false )
$data string

The data to be protected

$key string

The secret key to be used for generating hash. Should be a secure cryptographic key.

$rawHash boolean

Whether the generated hash value is in raw binary format. If false, lowercase hex digits will be generated.

return string

The data prefixed with the keyed hash

throws yii\base\InvalidConfigException

when HMAC generation fails.

hkdf() public method

Derives a key from the given input key using the standard HKDF algorithm.

Implements HKDF specified in RFC 5869. Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.

public string hkdf ( $algo, $inputKey, $salt null, $info null, $length 0 )
$algo string

A hash algorithm supported by hash_hmac(), e.g. 'SHA-256'

$inputKey string

The source key

$salt string

The random salt

$info string

Optional info to bind the derived key material to application- and context-specific information, e.g. a user ID or API version, see RFC 5869

$length integer

Length of the output key in bytes. If 0, the output key is the length of the hash algorithm output.

return string

The derived key

throws yii\base\InvalidParamException

when HMAC generation fails.

maskToken() public method (available since version 2.0.12)

Masks a token to make it uncompressible.

Applies a random mask to the token and prepends the mask used to the result making the string always unique. Used to mitigate BREACH attack by randomizing how token is outputted on each request.

public string maskToken ( $token )
$token string

An unmasked token.

return string

A masked token.

pbkdf2() public method

Derives a key from the given password using the standard PBKDF2 algorithm.

Implements HKDF2 specified in RFC 2898 Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.

public string pbkdf2 ( $algo, $password, $salt, $iterations, $length 0 )
$algo string

A hash algorithm supported by hash_hmac(), e.g. 'SHA-256'

$password string

The source password

$salt string

The random salt

$iterations integer

The number of iterations of the hash algorithm. Set as high as possible to hinder dictionary password attacks.

$length integer

Length of the output key in bytes. If 0, the output key is the length of the hash algorithm output.

return string

The derived key

throws yii\base\InvalidParamException

when hash generation fails due to invalid params given.

unmaskToken() public method (available since version 2.0.12)

Unmasks a token previously masked by maskToken.

public string unmaskToken ( $maskedToken )
$maskedToken string

A masked token.

return string

An unmasked token, or an empty string in case of token format is invalid.

validateData() public method

Validates if the given data is tampered.

See also hashData().

public string|false validateData ( $data, $key, $rawHash false )
$data string

The data to be validated. The data must be previously generated by hashData().

$key string

The secret key that was previously used to generate the hash for the data in hashData(). function to see the supported hashing algorithms on your system. This must be the same as the value passed to hashData() when generating the hash for the data.

$rawHash boolean

This should take the same value as when you generate the data using hashData(). It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists of lowercase hex digits only. hex digits will be generated.

return string|false

The real data with the hash stripped off. False if the data is tampered.

throws yii\base\InvalidConfigException

when HMAC generation fails.

validatePassword() public method

Verifies a password against a hash.

See also generatePasswordHash().

public boolean validatePassword ( $password, $hash )
$password string

The password to verify.

$hash string

The hash to verify the password against.

return boolean

Whether the password is correct.

throws yii\base\InvalidParamException

on bad password/hash parameters or if crypt() with Blowfish hash is not available.