Skip to content
PHP Ecosystem
Explore

Security

API reference › yii › base › Security

classyii\base\Security
ExtendsComponent » BaseObject
ImplementsConfigurable
Since2.0
Sourceframework/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.

PropertyTypeDescriptionDefined by
$allowedCiphersarray[]Look-up table of block sizes and key sizes for each supported OpenSSL cipher. Default: ['AES-128-CBC' => [16, 16], 'AES-192-CBC' => [16, 24], 'AES-256-CBC' => [16, 32]].Security
$authKeyInfostringHKDF info value for derivation of message authentication key. Default: 'AuthorizationKey'.Security
$behaviors read-onlyarray<Behavior<static>>List of behaviors attached to this component.Component
$cipherstringThe cipher to use for encryption and decryption. Default: 'AES-128-CBC'.Security
$derivationIterationsintDerivation iterations count. Default: 100000.Security
$kdfHashstringHash algorithm for key derivation. Default: 'sha256'.Security
$macHashstringHash algorithm for message authentication. Default: 'sha256'.Security
$passwordHashCostintDefault cost used for password hashing. Default: 13. Available since 2.0.6.Security
MethodDescriptionDefined by
__construct()Constructor.BaseObject
__call()Calls the named method which is not a class method.Component
__clone()This method is called after the object is created by cloning an existing one.Component
__get()Returns the value of a component property.Component
__isset()Checks if a property is set, i.e. defined and not null.Component
__set()Sets the value of a component property.Component
__unset()Sets a component property to be null.Component
attachBehavior()Attaches a behavior to this component.Component
attachBehaviors()Attaches a list of behaviors to the component.Component
behaviors()Returns a list of behaviors that this component should behave as.Component
canGetProperty()Returns a value indicating whether a property can be read.Component
canSetProperty()Returns a value indicating whether a property can be set.Component
className() staticReturns the fully qualified name of this class.BaseObject
compareString()Performs string comparison using timing attack resistant approach.Security
decryptByKey()Verifies and decrypts data encrypted with encryptByKey().Security
decryptByPassword()Verifies and decrypts data encrypted with encryptByPassword().Security
detachBehavior()Detaches a behavior from the component.Component
detachBehaviors()Detaches all behaviors from the component.Component
encryptByKey()Encrypts data using a cryptographic key.Security
encryptByPassword()Encrypts data using a password.Security
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.Component
generatePasswordHash()Generates a secure hash from a password and a random salt.Security
generateRandomKey()Generates specified number of random bytes.Security
generateRandomString()Generates a random string of specified length.Security
getBehavior()Returns the named behavior object.Component
getBehaviors()Returns all behaviors attached to this component.Component
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.Component
hashData()Prefixes data with a keyed hash value so that it can later be detected if it is tampered.Security
hasMethod()Returns a value indicating whether a method is defined.Component
hasProperty()Returns a value indicating whether a property is defined for this component.Component
hkdf()Derives a key from the given input key using the standard HKDF algorithm.Security
init()Initializes the object.BaseObject
maskToken()Masks a token to make it uncompressible.Security
off()Detaches an existing event handler from this component.Component
on()Attaches an event handler to an event.Component
pbkdf2()Derives a key from the given password using the standard PBKDF2 algorithm.Security
trigger()Triggers an event.Component
unmaskToken()Unmasks a token previously masked by maskToken.Security
validateData()Validates if the given data is tampered.Security
validatePassword()Verifies a password against a hash.Security
decrypt() protectedDecrypts data.Security
encrypt() protectedEncrypts data.Security
public array[] $allowedCiphers = ['AES-128-CBC' => [16, 16], 'AES-192-CBC' => [16, 24], 'AES-256-CBC' => [16, 32]]

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 int $derivationIterations = 100000

Derivation iterations count.

Set as high as possible to hinder dictionary password attacks.

public string $kdfHash = 'sha256'

Hash algorithm for key derivation.

Recommend sha256, sha384 or sha512.

public string $macHash = 'sha256'

Hash algorithm for message authentication.

Recommend sha256, sha384 or sha512.

public int $passwordHashCost = 13

Default cost used for password hashing.

Allowed value is between 4 and 31.

Since

2.0.6

public function compareString(string $expected, string $actual): bool

Performs string comparison using timing attack resistant approach.

Parameters

ParameterTypeDescription
$expectedstringString to compare.
$actualstringUser-supplied string.

Returns

bool: Whether strings are equal.

See also

public function decryptByKey(string $data, string $inputKey, string|null $info = null): bool|string

Verifies and decrypts data encrypted with encryptByKey().

Parameters

ParameterTypeDescription
$datastringThe encrypted data to decrypt
$inputKeystringThe input to use for encryption and authentication
$infostring|nullOptional context and application specific information, see hkdf()

Returns

bool|string: The decrypted data or false on authentication failure

See also

public function decryptByPassword(string $data, string $password): bool|string

Verifies and decrypts data encrypted with encryptByPassword().

Parameters

ParameterTypeDescription
$datastringThe encrypted data to decrypt
$passwordstringThe password to use for decryption

Returns

bool|string: The decrypted data or false on authentication failure

See also

public function encryptByKey(string $data, string $inputKey, string|null $info = null): string

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.

Parameters

ParameterTypeDescription
$datastringThe data to encrypt
$inputKeystringThe input to use for encryption and authentication
$infostring|nullOptional context and application specific information, see hkdf()

Returns

string: The encrypted data as byte string

See also

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

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.

Parameters

ParameterTypeDescription
$datastringThe data to encrypt
$passwordstringThe password to use for encryption

Returns

string: The encrypted data as byte string

See also

public function generatePasswordHash(string $password, int|null $cost = null): string

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
}

Parameters

ParameterTypeDescription
$passwordstringThe password to be hashed.
$costint|nullCost 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.

Returns

string: The password hash string. The output length might increase in future versions of PHP (https://www.php.net/manual/en/function.password-hash.php)

Throws

  • Exception: on bad password parameter or cost parameter.

See also

public function generateRandomKey(int $length = 32): string

Generates specified number of random bytes.

Note that output may not be ASCII.

Parameters

ParameterTypeDescription
$lengthintThe number of bytes to generate

Returns

string: The generated random bytes

Throws

See also

public function generateRandomString(int $length = 32): string

Generates a random string of specified length.

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

Parameters

ParameterTypeDescription
$lengthintThe length of the key in characters

Returns

string: The generated random key

Throws

public function hashData(string $data, string $key, bool $rawHash = false): string

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.

Parameters

ParameterTypeDescription
$datastringThe data to be protected
$keystringThe secret key to be used for generating hash. Should be a secure cryptographic key.
$rawHashboolWhether the generated hash value is in raw binary format. If false, lowercase hex digits will be generated.

Returns

string: The data prefixed with the keyed hash

Throws

See also

public function hkdf(string $algo, string $inputKey, string|null $salt = null, string|null $info = null, int $length = 0): string

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.

Parameters

ParameterTypeDescription
$algostringA hash algorithm supported by hash_hmac(), e.g. ‘SHA-256’
$inputKeystringThe source key
$saltstring|nullThe random salt
$infostring|nullOptional info to bind the derived key material to application- and context-specific information, e.g. a user ID or API version, see RFC 5869
$lengthintLength of the output key in bytes. If 0, the output key is the length of the hash algorithm output.

Returns

string: The derived key

Throws

public function maskToken(string $token): string

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.

Parameters

ParameterTypeDescription
$tokenstringAn unmasked token.

Returns

string: A masked token.

Since

2.0.12

public function pbkdf2(string $algo, string $password, string $salt, int $iterations, int $length = 0): string

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.

Parameters

ParameterTypeDescription
$algostringA hash algorithm supported by hash_hmac(), e.g. ‘SHA-256’
$passwordstringThe source password
$saltstringThe random salt
$iterationsintThe number of iterations of the hash algorithm. Set as high as possible to hinder dictionary password attacks.
$lengthintLength of the output key in bytes. If 0, the output key is the length of the hash algorithm output.

Returns

string: The derived key

Throws

public function unmaskToken(string $maskedToken): string

Unmasks a token previously masked by maskToken.

Parameters

ParameterTypeDescription
$maskedTokenstringA masked token.

Returns

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

Since

2.0.12

public function validateData(string $data, string $key, bool $rawHash = false): string|false

Validates if the given data is tampered.

Parameters

ParameterTypeDescription
$datastringThe data to be validated. The data must be previously generated by hashData().
$keystringThe 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.
$rawHashboolThis 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.

Returns

string|false: The real data with the hash stripped off. False if the data is tampered.

Throws

See also

public function validatePassword(string $password, string $hash): bool

Verifies a password against a hash.

Parameters

ParameterTypeDescription
$passwordstringThe password to verify.
$hashstringThe hash to verify the password against.

Returns

bool: Whether the password is correct.

Throws

See also

protected function decrypt(string $data, bool $passwordBased, string $secret, string|null $info): bool|string

Decrypts data.

Parameters

ParameterTypeDescription
$datastringEncrypted data to be decrypted.
$passwordBasedboolSet true to use password-based key derivation
$secretstringThe decryption password or key
$infostring|nullContext/application specific information, @see encrypt()

Returns

bool|string: The decrypted data or false on authentication failure

Throws

See also

protected function encrypt(string $data, bool $passwordBased, string $secret, string|null $info): string

Encrypts data.

Parameters

ParameterTypeDescription
$datastringData to be encrypted
$passwordBasedboolSet true to use password-based key derivation
$secretstringThe encryption password or key
$infostring|nullContext/application specific information, e.g. a user ID See RFC 5869 Section 3.2 for more details.

Returns

string: The encrypted data as byte string

Throws

See also