HumHub Documentation (unofficial)

Security extends Component
in package

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

In particular, Security supports the following features:

  • Encryption/decryption: [[encryptByKey()]], [[decryptByKey()]], [[encryptByPassword()]] and [[decryptByPassword()]]
  • Key derivation using standard algorithms: [[pbkdf2()]] and [[hkdf()]]
  • Data tampering prevention: [[hashData()]] and [[validateData()]]
  • Password validation: [[generatePasswordHash()]] and [[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.

Tags
author

Qiang Xue qiang.xue@gmail.com

author

Tom Worster fsb@thefsb.org

author

Klimov Paul klimov.paul@gmail.com

since
2.0

Table of Contents

Properties

$allowedCiphers  : array<string|int, array<string|int, mixed>>
$authKeyInfo  : string
$behaviors  : array<string|int, Behavior>
$cipher  : string
$derivationIterations  : int
$kdfHash  : string
$macHash  : string
$passwordHashCost  : int
$passwordHashStrategy  : string
$_behaviors  : array<string|int, Behavior>|null
$_events  : array<string|int, mixed>
$_eventWildcards  : array<string|int, mixed>
$_useLibreSSL  : bool

Methods

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

Properties

$allowedCiphers

public array<string|int, array<string|int, mixed>> $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.

$authKeyInfo

public string $authKeyInfo = 'AuthorizationKey'

HKDF info value for derivation of message authentication key.

Tags
see
hkdf()

$behaviors read-only

public array<string|int, Behavior> $behaviors

List of behaviors attached to this component.

$cipher

public string $cipher = 'AES-128-CBC'

The cipher to use for encryption and decryption.

$derivationIterations

public int $derivationIterations = 100000

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

$passwordHashCost

public int $passwordHashCost = 13

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

Tags
see
generatePasswordHash()
since
2.0.6

$passwordHashStrategy

public string $passwordHashStrategy

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.
Tags
deprecated

since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and uses password_hash() when available or crypt() when not.

$_behaviors

private array<string|int, Behavior>|null $_behaviors

the attached behaviors (behavior name => behavior). This is null when not initialized.

$_events

private array<string|int, mixed> $_events = []

the attached event handlers (event name => handlers)

$_eventWildcards

private array<string|int, mixed> $_eventWildcards = []

the event handlers attached for wildcard patterns (event name wildcard => handlers)

Tags
since
2.0.14

$_useLibreSSL

private bool $_useLibreSSL

if LibreSSL should be used. The recent (> 2.1.5) LibreSSL RNGs are faster and likely better than /dev/urandom.

Methods

__call()

Calls the named method which is not a class method.

public __call(string $name, array<string|int, mixed> $params) : mixed

This method will check if any attached behavior has the named method and will execute it if available.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

Parameters
$name : string

the method name

$params : array<string|int, mixed>

method parameters

Tags
throws
UnknownMethodException

when calling unknown method

Return values
mixed

the method return value

__clone()

This method is called after the object is created by cloning an existing one.

public __clone() : mixed

It removes all behaviors because they are attached to the old object.

__construct()

Constructor.

public __construct([array<string|int, mixed> $config = [] ]) : mixed

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call [[init()]].

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
Parameters
$config : array<string|int, mixed> = []

name-value pairs that will be used to initialize the object properties

__get()

Returns the value of a component property.

public __get(string $name) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a getter: return the getter result
  • a property of a behavior: return the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;.

Parameters
$name : string

the property name

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is write-only.

see
__set()
Return values
mixed

the property value or the value of a behavior's property

__isset()

Checks if a property is set, i.e. defined and not null.

public __isset(string $name) : bool

This method will check in the following order and act accordingly:

  • a property defined by a setter: return whether the property is set
  • a property of a behavior: return whether the property is set
  • return false for non existing properties

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property).

Parameters
$name : string

the property name or the event name

Tags
see
https://www.php.net/manual/en/function.isset.php
Return values
bool

whether the named property is set

__set()

Sets the value of a component property.

public __set(string $name, mixed $value) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value
  • an event in the format of "on xyz": attach the handler to the event "xyz"
  • a behavior in the format of "as xyz": attach the behavior named as "xyz"
  • a property of a behavior: set the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;.

Parameters
$name : string

the property name or the event name

$value : mixed

the property value

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is read-only.

see
__get()

__unset()

Sets a component property to be null.

public __unset(string $name) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value to be null
  • a property of a behavior: set the property value to be null

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property).

Parameters
$name : string

the property name

Tags
throws
InvalidCallException

if the property is read only.

see
https://www.php.net/manual/en/function.unset.php

attachBehavior()

Attaches a behavior to this component.

public attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior

This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.

Parameters
$name : string

the name of the behavior.

$behavior : string|array<string|int, mixed>|Behavior

the behavior configuration. This can be one of the following:

  • a [[Behavior]] object
  • a string specifying the behavior class
  • an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
see
detachBehavior()
Return values
Behavior

the behavior object

attachBehaviors()

Attaches a list of behaviors to the component.

public attachBehaviors(array<string|int, mixed> $behaviors) : mixed

Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.

Parameters
$behaviors : array<string|int, mixed>

list of behaviors to be attached to the component

Tags
see
attachBehavior()

behaviors()

Returns a list of behaviors that this component should behave as.

public behaviors() : array<string|int, mixed>

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from [[Behavior]]. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using [[getBehavior()]] or be detached using [[detachBehavior()]]. Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

Return values
array<string|int, mixed>

the behavior configurations.

canGetProperty()

Returns a value indicating whether a property can be read.

public canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property can be read if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a readable property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canSetProperty()
Return values
bool

whether the property can be read

canSetProperty()

Returns a value indicating whether a property can be set.

public canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property can be written if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a writable property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
Return values
bool

whether the property can be written

className()

Returns the fully qualified name of this class.

public static className() : string
Tags
deprecated

since 2.0.14. On PHP >=5.5, use ::class instead.

Return values
string

the fully qualified name of this class.

compareString()

Performs string comparison using timing attack resistant approach.

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

string to compare.

$actual : string

user-supplied string.

Tags
see
https://codereview.stackexchange.com/q/13512
Return values
bool

whether strings are equal.

decryptByKey()

Verifies and decrypts data encrypted with [[encryptByKey()]].

public decryptByKey(string $data, string $inputKey[, string|null $info = null ]) : bool|string
Parameters
$data : string

the encrypted data to decrypt

$inputKey : string

the input to use for encryption and authentication

$info : string|null = null

optional context and application specific information, see [[hkdf()]]

Tags
see
encryptByKey()
Return values
bool|string

the decrypted data or false on authentication failure

decryptByPassword()

Verifies and decrypts data encrypted with [[encryptByPassword()]].

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

the encrypted data to decrypt

$password : string

the password to use for decryption

Tags
see
encryptByPassword()
Return values
bool|string

the decrypted data or false on authentication failure

detachBehavior()

Detaches a behavior from the component.

public detachBehavior(string $name) : Behavior|null

The behavior's [[Behavior::detach()]] method will be invoked.

Parameters
$name : string

the behavior's name.

Return values
Behavior|null

the detached behavior. Null if the behavior does not exist.

detachBehaviors()

Detaches all behaviors from the component.

public detachBehaviors() : mixed

encryptByKey()

Encrypts data using a cryptographic key.

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

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
$data : string

the data to encrypt

$inputKey : string

the input to use for encryption and authentication

$info : string|null = null

optional context and application specific information, see [[hkdf()]]

Tags
see
decryptByKey()
see
encryptByPassword()
Return values
string

the encrypted data as byte string

encryptByPassword()

Encrypts data using a password.

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

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
$data : string

the data to encrypt

$password : string

the password to use for encryption

Tags
see
decryptByPassword()
see
encryptByKey()
Return values
string

the encrypted data as byte string

ensureBehaviors()

Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.

public ensureBehaviors() : mixed

generatePasswordHash()

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

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

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
$password : string

The password to be hashed.

$cost : int|null = 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.

Tags
throws
Exception

on bad password parameter or cost parameter.

see
validatePassword()
Return values
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 (https://www.php.net/manual/en/function.password-hash.php)

generateRandomKey()

Generates specified number of random bytes.

public generateRandomKey([int $length = 32 ]) : string

Note that output may not be ASCII.

Parameters
$length : int = 32

the number of bytes to generate

Tags
see
generateRandomString()

if you need a string.

throws
InvalidArgumentException

if wrong length is specified

throws
Exception

on failure.

Return values
string

the generated random bytes

generateRandomString()

Generates a random string of specified length.

public generateRandomString([int $length = 32 ]) : string

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

Parameters
$length : int = 32

the length of the key in characters

Tags
throws
Exception

on failure.

Return values
string

the generated random key

getBehavior()

Returns the named behavior object.

public getBehavior(string $name) : Behavior|null
Parameters
$name : string

the behavior name

Return values
Behavior|null

the behavior object, or null if the behavior does not exist

getBehaviors()

Returns all behaviors attached to this component.

public getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior>

list of behaviors attached to this component

hasEventHandlers()

Returns a value indicating whether there is any handler attached to the named event.

public hasEventHandlers(string $name) : bool
Parameters
$name : string

the event name

Return values
bool

whether there is any handler attached to the event.

hashData()

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

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

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

Parameters
$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 = false

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

Tags
throws
InvalidConfigException

when HMAC generation fails.

see
validateData()
see
generateRandomKey()
see
hkdf()
see
pbkdf2()
Return values
string

the data prefixed with the keyed hash

hasMethod()

Returns a value indicating whether a method is defined.

public hasMethod(string $name[, bool $checkBehaviors = true ]) : bool

A method is defined if:

  • the class has a method with the specified name
  • an attached behavior has a method with the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkBehaviors : bool = true

whether to treat behaviors' methods as methods of this component

Return values
bool

whether the method is defined

hasProperty()

Returns a value indicating whether a property is defined for this component.

public hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
see
canSetProperty()
Return values
bool

whether the property is defined

hkdf()

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

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

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

Parameters
$algo : string

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

$inputKey : string

the source key

$salt : string|null = null

the random salt

$info : string|null = 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

$length : int = 0

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

Tags
throws
InvalidArgumentException

when HMAC generation fails.

Return values
string

the derived key

init()

Initializes the object.

public init() : mixed

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

maskToken()

Masks a token to make it uncompressible.

public maskToken(string $token) : string

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
$token : string

An unmasked token.

Tags
since
2.0.12
Return values
string

A masked token.

off()

Detaches an existing event handler from this component.

public off(string $name[, callable|null $handler = null ]) : bool

This method is the opposite of [[on()]].

Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.

Parameters
$name : string

event name

$handler : callable|null = null

the event handler to be removed. If it is null, all handlers attached to the named event will be removed.

Tags
see
on()
Return values
bool

if a handler is found and detached

on()

Attaches an event handler to an event.

public on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed

The event handler must be a valid PHP callback. The following are some examples:

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

The event handler must be defined with the following signature,

function ($event)

where $event is an [[Event]] object which includes parameters associated with the event.

Since 2.0.14 you can specify event name as a wildcard pattern:

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});
Parameters
$name : string

the event name

$handler : callable

the event handler

$data : mixed = null

the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]].

$append : bool = true

whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.

Tags
see
off()

pbkdf2()

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

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

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

Parameters
$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 = 0

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

Tags
throws
InvalidArgumentException

when hash generation fails due to invalid params given.

Return values
string

the derived key

trigger()

Triggers an event.

public trigger(string $name[, Event|null $event = null ]) : mixed

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

Parameters
$name : string

the event name

$event : Event|null = null

the event instance. If not set, a default [[Event]] object will be created.

unmaskToken()

Unmasks a token previously masked by `maskToken`.

public unmaskToken(string $maskedToken) : string
Parameters
$maskedToken : string

A masked token.

Tags
since
2.0.12
Return values
string

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

validateData()

Validates if the given data is tampered.

public validateData(string $data, string $key[, bool $rawHash = false ]) : string|false
Parameters
$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 = false

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.

Tags
throws
InvalidConfigException

when HMAC generation fails.

see
hashData()
Return values
string|false

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

validatePassword()

Verifies a password against a hash.

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

The password to verify.

$hash : string

The hash to verify the password against.

Tags
throws
InvalidArgumentException

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

see
generatePasswordHash()
Return values
bool

whether the password is correct.

decrypt()

Decrypts data.

protected decrypt(string $data, bool $passwordBased, string $secret, string|null $info) : bool|string
Parameters
$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()

Tags
throws
InvalidConfigException

on OpenSSL not loaded

throws
Exception

on OpenSSL error

see
encrypt()
Return values
bool|string

the decrypted data or false on authentication failure

encrypt()

Encrypts data.

protected encrypt(string $data, bool $passwordBased, string $secret, string|null $info) : string
Parameters
$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 for more details.

Tags
throws
InvalidConfigException

on OpenSSL not loaded

throws
Exception

on OpenSSL error

see
decrypt()
Return values
string

the encrypted data as byte string

generateSalt()

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

protected generateSalt([int $cost = 13 ]) : string

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".

Parameters
$cost : int = 13

the cost parameter

Tags
throws
InvalidArgumentException

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

Return values
string

the random salt value.

shouldUseLibreSSL()

protected shouldUseLibreSSL() : bool
Tags
since
2.0.36
Return values
bool

if LibreSSL should be used Use version is 2.1.5 or higher.

attachBehaviorInternal()

Attaches a behavior to this component.

private attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
$name : string|int

the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.

$behavior : string|array<string|int, mixed>|Behavior

the behavior to be attached

Return values
Behavior

the attached behavior.


        
On this page

Search results