PHP Class yii\base\Security

In particular, Security supports the following features: - Encryption/decryption: Security::encryptByKey, Security::decryptByKey, Security::encryptByPassword and Security::decryptByPassword - Key derivation using standard algorithms: Security::pbkdf2 and Security::hkdf - Data tampering prevention: Security::hashData and Security::validateData - Password validation: Security::generatePasswordHash and Security::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.
Since: 2.0
Author: Qiang Xue ([email protected])
Author: Tom Worster ([email protected])
Author: Klimov Paul ([email protected])
Inheritance: extends Component
Show file Open project: yiisoft/yii2 Class Usage Examples

Public Properties

Property Type Description
$allowedCiphers 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 HKDF info value for derivation of message authentication key.
$cipher The cipher to use for encryption and decryption.
$derivationIterations derivation iterations count. Set as high as possible to hinder dictionary password attacks.
$kdfHash Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
$macHash Hash algorithm for message authentication. Recommend sha256, sha384 or sha512.
$passwordHashCost Default cost used for password hashing. Allowed value is between 4 and 31.
$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.

Public Methods

Method Description
compareString ( string $expected, string $actual ) : boolean Performs string comparison using timing attack resistant approach.
decryptByKey ( string $data, string $inputKey, string $info = null ) : boolean | string Verifies and decrypts data encrypted with Security::encryptByKey.
decryptByPassword ( string $data, string $password ) : boolean | string Verifies and decrypts data encrypted with Security::encryptByPassword.
encryptByKey ( string $data, string $inputKey, string $info = null ) : string Encrypts data using a cryptographic key.
encryptByPassword ( string $data, string $password ) : string Encrypts data using a password.
generatePasswordHash ( string $password, integer $cost = null ) : string Generates a secure hash from a password and a random salt.
generateRandomKey ( integer $length = 32 ) : string Generates specified number of random bytes.
generateRandomString ( integer $length = 32 ) : string Generates a random string of specified length.
hashData ( string $data, string $key, boolean $rawHash = false ) : string Prefixes data with a keyed hash value so that it can later be detected if it is tampered.
hkdf ( string $algo, string $inputKey, string $salt = null, string $info = null, integer $length ) : string Derives a key from the given input key using the standard HKDF algorithm.
pbkdf2 ( string $algo, string $password, string $salt, integer $iterations, integer $length ) : string Derives a key from the given password using the standard PBKDF2 algorithm.
validateData ( string $data, string $key, boolean $rawHash = false ) : string Validates if the given data is tampered.
validatePassword ( string $password, string $hash ) : boolean Verifies a password against a hash.

Protected Methods

Method Description
decrypt ( string $data, boolean $passwordBased, string $secret, string $info ) : boolean | string Decrypts data.
encrypt ( string $data, boolean $passwordBased, string $secret, string $info ) : string Encrypts data.
generateSalt ( integer $cost = 13 ) : string Generates a salt that can be used to generate a password hash.

Method Details

compareString() public method

Performs string comparison using timing attack resistant approach.
See also: http://codereview.stackexchange.com/questions/13512
public compareString ( string $expected, string $actual ) : boolean
$expected string string to compare.
$actual string user-supplied string.
return boolean whether strings are equal.

decrypt() protected method

Decrypts data.
See also: encrypt()
protected decrypt ( string $data, boolean $passwordBased, string $secret, string $info ) : boolean | string
$data string encrypted data to be decrypted.
$passwordBased boolean set true to use password-based key derivation
$secret string the decryption password or key
$info string context/application specific information, @see encrypt()
return boolean | string the decrypted data or false on authentication failure

decryptByKey() public method

Verifies and decrypts data encrypted with Security::encryptByKey.
See also: encryptByKey()
public decryptByKey ( string $data, string $inputKey, string $info = null ) : boolean | string
$data string the encrypted data to decrypt
$inputKey string the input to use for encryption and authentication
$info string optional context and application specific information, see [[hkdf()]]
return boolean | string the decrypted data or false on authentication failure

decryptByPassword() public method

Verifies and decrypts data encrypted with Security::encryptByPassword.
See also: encryptByPassword()
public decryptByPassword ( string $data, string $password ) : boolean | string
$data string the encrypted data to decrypt
$password string the password to use for decryption
return boolean | string the decrypted data or false on authentication failure

encrypt() protected method

Encrypts data.
See also: decrypt()
protected encrypt ( string $data, boolean $passwordBased, string $secret, string $info ) : string
$data string data to be encrypted
$passwordBased boolean set true to use password-based key derivation
$secret string the encryption password or key
$info string 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.
return string the encrypted data

encryptByKey() public method

Derives keys for encryption and authentication from the input key using HKDF and a random salt, which is very fast relative to Security::encryptByPassword. The input key must be properly random -- use Security::generateRandomKey to generate keys. The encrypted data includes a keyed message authentication code (MAC) so there is no need to hash input or output data.
See also: decryptByKey()
See also: encryptByPassword()
public encryptByKey ( string $data, string $inputKey, string $info = null ) : string
$data string the data to encrypt
$inputKey string the input to use for encryption and authentication
$info string optional context and application specific information, see [[hkdf()]]
return string the encrypted data

encryptByPassword() public method

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 Security::encryptByKey to encrypt fast using a cryptographic key rather than a password. Key derivation time is determined by [[$derivationIterations]], which should be set as high as possible. The encrypted data includes a keyed message authentication code (MAC) so there is no need to hash input or output data. > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against poor-quality or compromised passwords.
See also: decryptByPassword()
See also: encryptByKey()
public encryptByPassword ( string $data, string $password ) : string
$data string the data to encrypt
$password string the password to use for encryption
return string the encrypted data

generatePasswordHash() public method

The generated hash can be stored in database. Later when a password needs to be validated, the hash can be fetched and passed to Security::validatePassword. For example, php generates the hash (usually done during user registration or when the password is changed) $hash = Yii::$app->getSecurity()->generatePasswordHash($password); ...save $hash in database... during login, validate if the password entered is correct using $hash fetched from database if (Yii::$app->getSecurity()->validatePassword($password, $hash) { password is good } else { password is bad }
See also: validatePassword()
public generatePasswordHash ( string $password, integer $cost = null ) : string
$password string The password to be hashed.
$cost integer Cost parameter used by the Blowfish hash algorithm. The higher the value of cost, the longer it takes to generate the hash and to verify a password against it. Higher cost therefore slows down a brute-force attack. For best protection against brute-force attacks, set it to the highest value that is tolerable on production servers. The time taken to compute the hash doubles for every increment by one of $cost.
return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt', the output is always 60 ASCII characters, when set to 'password_hash' the output length might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)

generateRandomKey() public method

Note that output may not be ASCII.
See also: generateRandomString() if you need a string.
public generateRandomKey ( integer $length = 32 ) : string
$length integer the number of bytes to generate
return string the generated random bytes

generateRandomString() public method

The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
public generateRandomString ( integer $length = 32 ) : string
$length integer the length of the key in characters
return string the generated random key

generateSalt() protected method

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

hashData() public method

There is no need to hash inputs or outputs of Security::encryptByKey or Security::encryptByPassword as those methods perform the task.
See also: validateData()
See also: generateRandomKey()
See also: hkdf()
See also: pbkdf2()
public hashData ( string $data, string $key, boolean $rawHash = false ) : string
$data string the data to be protected
$key string the secret key to be used for generating hash. Should be a secure cryptographic key.
$rawHash boolean whether the generated hash value is in raw binary format. If false, lowercase hex digits will be generated.
return string the data prefixed with the keyed hash

hkdf() public method

Implements HKDF specified in RFC 5869. Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
public hkdf ( string $algo, string $inputKey, string $salt = null, string $info = null, integer $length ) : string
$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](https://tools.ietf.org/html/rfc5869)
$length integer length of the output key in bytes. If 0, the output key is the length of the hash algorithm output.
return string the derived key

pbkdf2() public method

Implements HKDF2 specified in RFC 2898 Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
public pbkdf2 ( string $algo, string $password, string $salt, integer $iterations, integer $length ) : string
$algo string a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
$password string the source password
$salt string the random salt
$iterations integer the number of iterations of the hash algorithm. Set as high as possible to hinder dictionary password attacks.
$length integer length of the output key in bytes. If 0, the output key is the length of the hash algorithm output.
return string the derived key

validateData() public method

Validates if the given data is tampered.
See also: hashData()
public validateData ( string $data, string $key, boolean $rawHash = false ) : string
$data string the data to be validated. The data must be previously generated by [[hashData()]].
$key string the secret key that was previously used to generate the hash for the data in [[hashData()]]. function to see the supported hashing algorithms on your system. This must be the same as the value passed to [[hashData()]] when generating the hash for the data.
$rawHash boolean this should take the same value as when you generate the data using [[hashData()]]. It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists of lowercase hex digits only. hex digits will be generated.
return string the real data with the hash stripped off. False if the data is tampered.

validatePassword() public method

Verifies a password against a hash.
See also: generatePasswordHash()
public validatePassword ( string $password, string $hash ) : boolean
$password string The password to verify.
$hash string The hash to verify the password against.
return boolean whether the password is correct.

Property Details

$allowedCiphers public property

Look-up table of block sizes and key sizes for each supported OpenSSL cipher. In each element, the key is one of the ciphers supported by OpenSSL (@see openssl_get_cipher_methods()). The value is an array of two integers, the first is the cipher's block size in bytes and the second is the key size in bytes. > Warning: All OpenSSL ciphers that we recommend are in the default value, i.e. AES in CBC mode. > Note: Yii's encryption protocol uses the same size for cipher key, HMAC signature key and key derivation salt.
public $allowedCiphers

$authKeyInfo public property

HKDF info value for derivation of message authentication key.
See also: hkdf()
public $authKeyInfo

$cipher public property

The cipher to use for encryption and decryption.
public $cipher

$derivationIterations public property

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

$kdfHash public property

Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
See also: [hash_algos()](http://php.net/manual/en/function.hash-algos.php)
public $kdfHash

$macHash public property

Hash algorithm for message authentication. Recommend sha256, sha384 or sha512.
See also: [hash_algos()](http://php.net/manual/en/function.hash-algos.php)
public $macHash

$passwordHashCost public property

Default cost used for password hashing. Allowed value is between 4 and 31.
See also: generatePasswordHash()
Since: 2.0.6
public $passwordHashCost

$passwordHashStrategy public property

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.
Deprecation: since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and uses `password_hash()` when available or `crypt()` when not.
public $passwordHashStrategy