PHP Класс 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.
С версии: 2.0
Автор: Qiang Xue ([email protected])
Автор: Tom Worster ([email protected])
Автор: Klimov Paul ([email protected])
Наследование: extends Component
Показать файл Открыть проект Примеры использования класса

Открытые свойства

Свойство Тип Описание
$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.

Открытые методы

Метод Описание
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.

Защищенные методы

Метод Описание
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.

Описание методов

compareString() публичный Метод

Performs string comparison using timing attack resistant approach.
См. также: http://codereview.stackexchange.com/questions/13512
public compareString ( string $expected, string $actual ) : boolean
$expected string string to compare.
$actual string user-supplied string.
Результат boolean whether strings are equal.

decrypt() защищенный Метод

Decrypts data.
См. также: 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()
Результат boolean | string the decrypted data or false on authentication failure

decryptByKey() публичный Метод

Verifies and decrypts data encrypted with Security::encryptByKey.
См. также: 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()]]
Результат boolean | string the decrypted data or false on authentication failure

decryptByPassword() публичный Метод

Verifies and decrypts data encrypted with Security::encryptByPassword.
См. также: encryptByPassword()
public decryptByPassword ( string $data, string $password ) : boolean | string
$data string the encrypted data to decrypt
$password string the password to use for decryption
Результат boolean | string the decrypted data or false on authentication failure

encrypt() защищенный Метод

Encrypts data.
См. также: 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.
Результат string the encrypted data

encryptByKey() публичный Метод

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.
См. также: decryptByKey()
См. также: 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()]]
Результат string the encrypted data

encryptByPassword() публичный Метод

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.
См. также: decryptByPassword()
См. также: encryptByKey()
public encryptByPassword ( string $data, string $password ) : string
$data string the data to encrypt
$password string the password to use for encryption
Результат string the encrypted data

generatePasswordHash() публичный Метод

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 }
См. также: 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.
Результат 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() публичный Метод

Note that output may not be ASCII.
См. также: generateRandomString() if you need a string.
public generateRandomKey ( integer $length = 32 ) : string
$length integer the number of bytes to generate
Результат string the generated random bytes

generateRandomString() публичный Метод

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
Результат string the generated random key

generateSalt() защищенный Метод

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
Результат string the random salt value.

hashData() публичный Метод

There is no need to hash inputs or outputs of Security::encryptByKey or Security::encryptByPassword as those methods perform the task.
См. также: validateData()
См. также: generateRandomKey()
См. также: hkdf()
См. также: 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.
Результат string the data prefixed with the keyed hash

hkdf() публичный Метод

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.
Результат string the derived key

pbkdf2() публичный Метод

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.
Результат string the derived key

validateData() публичный Метод

Validates if the given data is tampered.
См. также: 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.
Результат string the real data with the hash stripped off. False if the data is tampered.

validatePassword() публичный Метод

Verifies a password against a hash.
См. также: generatePasswordHash()
public validatePassword ( string $password, string $hash ) : boolean
$password string The password to verify.
$hash string The hash to verify the password against.
Результат boolean whether the password is correct.

Описание свойств

$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.
public $allowedCiphers

$authKeyInfo публичное свойство

HKDF info value for derivation of message authentication key.
См. также: hkdf()
public $authKeyInfo

$cipher публичное свойство

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

$derivationIterations публичное свойство

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

$kdfHash публичное свойство

Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
См. также: [hash_algos()](http://php.net/manual/en/function.hash-algos.php)
public $kdfHash

$macHash публичное свойство

Hash algorithm for message authentication. Recommend sha256, sha384 or sha512.
См. также: [hash_algos()](http://php.net/manual/en/function.hash-algos.php)
public $macHash

$passwordHashCost публичное свойство

Default cost used for password hashing. Allowed value is between 4 and 31.
См. также: generatePasswordHash()
С версии: 2.0.6
public $passwordHashCost

$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.
Устаревший: since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and uses `password_hash()` when available or `crypt()` when not.
public $passwordHashStrategy