Security
API reference › yii › base › Security
Security provides a set of methods to handle common security-related tasks.
In particular, Security supports the following features:
- Encryption/decryption:
encryptByKey(),decryptByKey(),encryptByPassword()anddecryptByPassword() - Key derivation using standard algorithms:
pbkdf2()andhkdf() - Data tampering prevention:
hashData()andvalidateData() - Password validation:
generatePasswordHash()andvalidatePassword()
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.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$allowedCiphers | array[] | Look-up table of block sizes and key sizes for each supported OpenSSL cipher. Default: ['AES-128-CBC' => [16,. | Security |
$authKeyInfo | string | HKDF info value for derivation of message authentication key. Default: 'AuthorizationKey'. | Security |
$behaviors read-only | array<Behavior<static>> | List of behaviors attached to this component. | Component |
$cipher | string | The cipher to use for encryption and decryption. Default: 'AES-128-CBC'. | Security |
$derivationIterations | int | Derivation iterations count. Default: 100000. | Security |
$kdfHash | string | Hash algorithm for key derivation. Default: 'sha256'. | Security |
$macHash | string | Hash algorithm for message authentication. Default: 'sha256'. | Security |
$passwordHashCost | int | Default cost used for password hashing. Default: 13. Available since 2.0.6. | Security |
Methods
Section titled “Methods”| Method | Description | Defined 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() static | Returns 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() protected | Decrypts data. | Security |
encrypt() protected | Encrypts data. | Security |
Property details
Section titled “Property details”$allowedCiphers
Section titled “$allowedCiphers ”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.
$derivationIterations
Section titled “$derivationIterations ”public int $derivationIterations = 100000Derivation iterations count.
Set as high as possible to hinder dictionary password attacks.
$kdfHash
Section titled “$kdfHash ”public string $kdfHash = 'sha256'Hash algorithm for key derivation.
Recommend sha256, sha384 or sha512.
$macHash
Section titled “$macHash ”public string $macHash = 'sha256'Hash algorithm for message authentication.
Recommend sha256, sha384 or sha512.
$passwordHashCost
Section titled “$passwordHashCost ”public int $passwordHashCost = 13Default cost used for password hashing.
Allowed value is between 4 and 31.
Since
2.0.6
Method details
Section titled “Method details”compareString()
Section titled “compareString() ”public function compareString(string $expected, string $actual): boolPerforms string comparison using timing attack resistant approach.
Parameters
| Parameter | Type | Description |
|---|---|---|
$expected | string | String to compare. |
$actual | string | User-supplied string. |
Returns
bool: Whether strings are equal.
See also
decryptByKey()
Section titled “decryptByKey() ”public function decryptByKey(string $data, string $inputKey, string|null $info = null): bool|stringVerifies and decrypts data encrypted with encryptByKey().
Parameters
| Parameter | Type | Description |
|---|---|---|
$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() |
Returns
bool|string: The decrypted data or false on authentication failure
See also
decryptByPassword()
Section titled “decryptByPassword() ”public function decryptByPassword(string $data, string $password): bool|stringVerifies and decrypts data encrypted with encryptByPassword().
Parameters
| Parameter | Type | Description |
|---|---|---|
$data | string | The encrypted data to decrypt |
$password | string | The password to use for decryption |
Returns
bool|string: The decrypted data or false on authentication failure
See also
encryptByKey()
Section titled “encryptByKey() ”public function encryptByKey(string $data, string $inputKey, string|null $info = null): stringEncrypts 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
| Parameter | Type | Description |
|---|---|---|
$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() |
Returns
string: The encrypted data as byte string
See also
encryptByPassword()
Section titled “encryptByPassword() ”public function encryptByPassword(string $data, string $password): stringEncrypts 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
| Parameter | Type | Description |
|---|---|---|
$data | string | The data to encrypt |
$password | string | The password to use for encryption |
Returns
string: The encrypted data as byte string
See also
generatePasswordHash()
Section titled “generatePasswordHash() ”public function generatePasswordHash(string $password, int|null $cost = null): stringGenerates 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 databaseif (Yii::$app->getSecurity()->validatePassword($password, $hash)) { // password is good} else { // password is bad}Parameters
| Parameter | Type | Description |
|---|---|---|
$password | string | The password to be hashed. |
$cost | int| | 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. |
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
generateRandomKey()
Section titled “generateRandomKey() ”public function generateRandomKey(int $length = 32): stringGenerates specified number of random bytes.
Note that output may not be ASCII.
Parameters
| Parameter | Type | Description |
|---|---|---|
$length | int | The number of bytes to generate |
Returns
string: The generated random bytes
Throws
InvalidArgumentException: if wrong length is specifiedException: on failure.
See also
generateRandomString()(if you need a string.)
generateRandomString()
Section titled “generateRandomString() ”public function generateRandomString(int $length = 32): stringGenerates a random string of specified length.
The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
Parameters
| Parameter | Type | Description |
|---|---|---|
$length | int | The length of the key in characters |
Returns
string: The generated random key
Throws
Exception: on failure.
hashData()
Section titled “hashData() ”public function hashData(string $data, string $key, bool $rawHash = false): stringPrefixes 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
| Parameter | Type | Description |
|---|---|---|
$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 | bool | Whether 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
InvalidConfigException: when HMAC generation fails.
See also
hkdf()
Section titled “hkdf() ”public function hkdf(string $algo, string $inputKey, string|null $salt = null, string|null $info = null, int $length = 0): stringDerives 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
| Parameter | Type | Description |
|---|---|---|
$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 | int | Length 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
InvalidArgumentException: when HMAC generation fails.
maskToken()
Section titled “maskToken() ”public function maskToken(string $token): stringMasks 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
| Parameter | Type | Description |
|---|---|---|
$token | string | An unmasked token. |
Returns
string: A masked token.
Since
2.0.12
pbkdf2()
Section titled “pbkdf2() ”public function pbkdf2(string $algo, string $password, string $salt, int $iterations, int $length = 0): stringDerives 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
| Parameter | Type | Description |
|---|---|---|
$algo | string | A hash algorithm supported by hash_hmac(), e.g. ‘SHA-256’ |
$password | string | The source password |
$salt | string | The random salt |
$iterations | int | The number of iterations of the hash algorithm. Set as high as possible to hinder dictionary password attacks. |
$length | int | Length 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
InvalidArgumentException: when hash generation fails due to invalid params given.
unmaskToken()
Section titled “unmaskToken() ”public function unmaskToken(string $maskedToken): stringUnmasks a token previously masked by maskToken.
Parameters
| Parameter | Type | Description |
|---|---|---|
$maskedToken | string | A masked token. |
Returns
string: An unmasked token, or an empty string in case of token format is invalid.
Since
2.0.12
validateData()
Section titled “validateData() ”public function validateData(string $data, string $key, bool $rawHash = false): string|falseValidates if the given data is tampered.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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 | bool | 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. |
Returns
string|false: The real data with the hash stripped off. False if the data is tampered.
Throws
InvalidConfigException: when HMAC generation fails.
See also
validatePassword()
Section titled “validatePassword() ”public function validatePassword(string $password, string $hash): boolVerifies a password against a hash.
Parameters
| Parameter | Type | Description |
|---|---|---|
$password | string | The password to verify. |
$hash | string | The hash to verify the password against. |
Returns
bool: Whether the password is correct.
Throws
InvalidArgumentException: on bad password/hash parameters.
See also
decrypt()
Section titled “decrypt() ”protected function decrypt(string $data, bool $passwordBased, string $secret, string|null $info): bool|stringDecrypts data.
Parameters
| Parameter | Type | Description |
|---|---|---|
$data | string | Encrypted data to be decrypted. |
$passwordBased | bool | Set true to use password-based key derivation |
$secret | string | The decryption password or key |
$info | string| | Context/application specific information, @see encrypt() |
Returns
bool|string: The decrypted data or false on authentication failure
Throws
InvalidConfigException: on OpenSSL not loadedException: on OpenSSL error
See also
encrypt()
Section titled “encrypt() ”protected function encrypt(string $data, bool $passwordBased, string $secret, string|null $info): stringEncrypts data.
Parameters
| Parameter | Type | Description |
|---|---|---|
$data | string | Data to be encrypted |
$passwordBased | bool | Set true to use password-based key derivation |
$secret | string | The encryption password or key |
$info | string| | Context/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
InvalidConfigException: on OpenSSL not loadedException: on OpenSSL error
See also