# Security

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

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [base](/docs/api/yii/base/index.md) › Security

| class | `yii\base\Security` |
| --- | --- |
| Extends | [`Component`](/docs/api/yii/base/component/index.md) » [`BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/base/Security.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/base/Security.php#L34) |

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

In particular, Security supports the following features:

- Encryption/decryption: [`encryptByKey()`](/docs/api/yii/base/security/index.md#method-encryptByKey), [`decryptByKey()`](/docs/api/yii/base/security/index.md#method-decryptByKey), [`encryptByPassword()`](/docs/api/yii/base/security/index.md#method-encryptByPassword) and [`decryptByPassword()`](/docs/api/yii/base/security/index.md#method-decryptByPassword)
- Key derivation using standard algorithms: [`pbkdf2()`](/docs/api/yii/base/security/index.md#method-pbkdf2) and [`hkdf()`](/docs/api/yii/base/security/index.md#method-hkdf)
- Data tampering prevention: [`hashData()`](/docs/api/yii/base/security/index.md#method-hashData) and [`validateData()`](/docs/api/yii/base/security/index.md#method-validateData)
- Password validation: [`generatePasswordHash()`](/docs/api/yii/base/security/index.md#method-generatePasswordHash) and [`validatePassword()`](/docs/api/yii/base/security/index.md#method-validatePassword)

> 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](/docs/guide/security-overview/index.md).

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| [`$allowedCiphers`](#property-allowedCiphers) | `array[]` | 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` |
| <span id="property-authKeyInfo"></span>`$authKeyInfo` | `string` | HKDF info value for derivation of message authentication key. Default: `'AuthorizationKey'`. | `Security` |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`Component`](/docs/api/yii/base/component/index.md) |
| <span id="property-cipher"></span>`$cipher` | `string` | The cipher to use for encryption and decryption. Default: `'AES-128-CBC'`. | `Security` |
| [`$derivationIterations`](#property-derivationIterations) | `int` | Derivation iterations count. Default: `100000`. | `Security` |
| [`$kdfHash`](#property-kdfHash) | `string` | Hash algorithm for key derivation. Default: `'sha256'`. | `Security` |
| [`$macHash`](#property-macHash) | `string` | Hash algorithm for message authentication. Default: `'sha256'`. | `Security` |
| [`$passwordHashCost`](#property-passwordHashCost) | `int` | Default cost used for password hashing. Default: `13`. Available since 2.0.6. | `Security` |

## Methods

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

## Property details

### $allowedCiphers <span id="property-allowedCiphers"></span>

```php
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 <span id="property-derivationIterations"></span>

```php
public int $derivationIterations = 100000
```

Derivation iterations count.

Set as high as possible to hinder dictionary password attacks.

### $kdfHash <span id="property-kdfHash"></span>

```php
public string $kdfHash = 'sha256'
```

Hash algorithm for key derivation.

Recommend sha256, sha384 or sha512.

### $macHash <span id="property-macHash"></span>

```php
public string $macHash = 'sha256'
```

Hash algorithm for message authentication.

Recommend sha256, sha384 or sha512.

### $passwordHashCost <span id="property-passwordHashCost"></span>

```php
public int $passwordHashCost = 13
```

Default cost used for password hashing.

Allowed value is between 4 and 31.

**Since**

2.0.6

## Method details

### compareString() <span id="method-compareString"></span>

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

Performs 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**

- <https://codereview.stackexchange.com/q/13512>

### decryptByKey() <span id="method-decryptByKey"></span>

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

Verifies and decrypts data encrypted with [`encryptByKey()`](/docs/api/yii/base/security/index.md#method-encryptByKey).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$data` | `string` | The encrypted data to decrypt |
| `$inputKey` | `string` | The input to use for encryption and authentication |
| `$info` | `string\|null` | Optional context and application specific information, see [`hkdf()`](/docs/api/yii/base/security/index.md#method-hkdf) |

**Returns**

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

**See also**

- [`encryptByKey()`](/docs/api/yii/base/security/index.md#method-encryptByKey)

### decryptByPassword() <span id="method-decryptByPassword"></span>

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

Verifies and decrypts data encrypted with [`encryptByPassword()`](/docs/api/yii/base/security/index.md#method-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**

- [`encryptByPassword()`](/docs/api/yii/base/security/index.md#method-encryptByPassword)

### encryptByKey() <span id="method-encryptByKey"></span>

```php
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()`](/docs/api/yii/base/security/index.md#method-encryptByPassword). The input key must be properly
random -- use [`generateRandomKey()`](/docs/api/yii/base/security/index.md#method-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\|null` | Optional context and application specific information, see [`hkdf()`](/docs/api/yii/base/security/index.md#method-hkdf) |

**Returns**

`string`: The encrypted data as byte string

**See also**

- [`decryptByKey()`](/docs/api/yii/base/security/index.md#method-decryptByKey)
- [`encryptByPassword()`](/docs/api/yii/base/security/index.md#method-encryptByPassword)

### encryptByPassword() <span id="method-encryptByPassword"></span>

```php
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()`](/docs/api/yii/base/security/index.md#method-encryptByKey) to
encrypt fast using a cryptographic key rather than a password. Key derivation time is
determined by [`$derivationIterations`](/docs/api/yii/base/security/index.md#property-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**

- [`decryptByPassword()`](/docs/api/yii/base/security/index.md#method-decryptByPassword)
- [`encryptByKey()`](/docs/api/yii/base/security/index.md#method-encryptByKey)

### generatePasswordHash() <span id="method-generatePasswordHash"></span>

```php
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()`](/docs/api/yii/base/security/index.md#method-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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$password` | `string` | The password to be hashed. |
| `$cost` | `int\|null` | 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`](/docs/api/yii/base/exception/index.md): on bad password parameter or cost parameter.

**See also**

- [`validatePassword()`](/docs/api/yii/base/security/index.md#method-validatePassword)

### generateRandomKey() <span id="method-generateRandomKey"></span>

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

Generates 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`](/docs/api/yii/base/invalidargumentexception/index.md): if wrong length is specified
- [`Exception`](/docs/api/yii/base/exception/index.md): on failure.

**See also**

- [`generateRandomString()`](/docs/api/yii/base/security/index.md#method-generateRandomString) (if you need a string.)

### generateRandomString() <span id="method-generateRandomString"></span>

```php
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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$length` | `int` | The length of the key in characters |

**Returns**

`string`: The generated random key

**Throws**

- [`Exception`](/docs/api/yii/base/exception/index.md): on failure.

### hashData() <span id="method-hashData"></span>

```php
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()`](/docs/api/yii/base/security/index.md#method-encryptByKey) or [`encryptByPassword()`](/docs/api/yii/base/security/index.md#method-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`](/docs/api/yii/base/invalidconfigexception/index.md): when HMAC generation fails.

**See also**

- [`validateData()`](/docs/api/yii/base/security/index.md#method-validateData)
- [`generateRandomKey()`](/docs/api/yii/base/security/index.md#method-generateRandomKey)
- [`hkdf()`](/docs/api/yii/base/security/index.md#method-hkdf)
- [`pbkdf2()`](/docs/api/yii/base/security/index.md#method-pbkdf2)

### hkdf() <span id="method-hkdf"></span>

```php
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](https://tools.ietf.org/html/rfc5869).
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\|null` | The random salt |
| `$info` | `string\|null` | 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](https://tools.ietf.org/html/rfc5869) |
| `$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`](/docs/api/yii/base/invalidargumentexception/index.md): when HMAC generation fails.

### maskToken() <span id="method-maskToken"></span>

```php
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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$token` | `string` | An unmasked token. |

**Returns**

`string`: A masked token.

**Since**

2.0.12

### pbkdf2() <span id="method-pbkdf2"></span>

```php
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](https://datatracker.ietf.org/doc/html/rfc2898#section-5.2)
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`](/docs/api/yii/base/invalidargumentexception/index.md): when hash generation fails due to invalid params given.

### unmaskToken() <span id="method-unmaskToken"></span>

```php
public function unmaskToken(string $maskedToken): string
```

Unmasks 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() <span id="method-validateData"></span>

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

Validates 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()`](/docs/api/yii/base/security/index.md#method-hashData). |
| `$key` | `string` | The secret key that was previously used to generate the hash for the data in [`hashData()`](/docs/api/yii/base/security/index.md#method-hashData). function to see the supported hashing algorithms on your system. This must be the same as the value passed to [`hashData()`](/docs/api/yii/base/security/index.md#method-hashData) when generating the hash for the data. |
| `$rawHash` | `bool` | This should take the same value as when you generate the data using [`hashData()`](/docs/api/yii/base/security/index.md#method-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`](/docs/api/yii/base/invalidconfigexception/index.md): when HMAC generation fails.

**See also**

- [`hashData()`](/docs/api/yii/base/security/index.md#method-hashData)

### validatePassword() <span id="method-validatePassword"></span>

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

Verifies 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`](/docs/api/yii/base/invalidargumentexception/index.md): on bad password/hash parameters.

**See also**

- [`generatePasswordHash()`](/docs/api/yii/base/security/index.md#method-generatePasswordHash)

### decrypt() <span id="method-decrypt"></span>

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

Decrypts 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\|null` | Context/application specific information, @see encrypt() |

**Returns**

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

**Throws**

- [`InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): on OpenSSL not loaded
- [`Exception`](/docs/api/yii/base/exception/index.md): on OpenSSL error

**See also**

- [`encrypt()`](/docs/api/yii/base/security/index.md#method-encrypt)

### encrypt() <span id="method-encrypt"></span>

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

Encrypts 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\|null` | Context/application specific information, e.g. a user ID See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details. |

**Returns**

`string`: The encrypted data as byte string

**Throws**

- [`InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): on OpenSSL not loaded
- [`Exception`](/docs/api/yii/base/exception/index.md): on OpenSSL error

**See also**

- [`decrypt()`](/docs/api/yii/base/security/index.md#method-decrypt)