Yii项目Security加密解密类提取
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
/**
* 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](guide:security-overview).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Tom Worster <fsb@thefsb.org>
* @author Klimov Paul <klimov.paul@gmail.com>
* @since 2.0
*/
class Security
{
/**
* @var string The cipher to use for encryption and decryption.
*/
public $cipher = 'AES-128-CBC';
/**
* @var array[] 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 = [
'AES-128-CBC' => [16, 16],
'AES-192-CBC' => [16, 24],
'AES-256-CBC' => [16, 32],
];
/**
* @var string Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
* @see [hash_algos()](http://php.net/manual/en/function.hash-algos.php)
*/
public $kdfHash = 'sha256';
/**
* @var string Hash algorithm for message authentication. Recommend sha256, sha384 or sha512.
* @see [hash_algos()](http://php.net/manual/en/function.hash-algos.php)
*/
public $macHash = 'sha256';
/**
* @var string HKDF info value for derivation of message authentication key.
* @see hkdf()
*/
public $authKeyInfo = 'AuthorizationKey';
/**
* @var int derivation iterations count.
* Set as high as possible to hinder dictionary password attacks.
*/
public $derivationIterations = 100000;
/**
* @var string 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.
* @deprecated since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and
* uses `password_hash()` when available or `crypt()` when not.
*/
public $passwordHashStrategy;
/**
* @var int Default cost used for password hashing.
* Allowed value is between 4 and 31.
* @see generatePasswordHash()
* @since 2.0.6
*/
public $passwordHashCost = 13;
/**
* 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()]] 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.
* @param string $data the data to encrypt
* @param string $password the password to use for encryption
* @return string the encrypted data
* @see decryptByPassword()
* @see encryptByKey()
*/
public function encryptByPassword($data, $password)
{
return $this->encrypt($data, true, $password, null);
}
/**
* 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()]]. 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.
* @param string $data the data to encrypt
* @param string $inputKey the input to use for encryption and authentication
* @param string $info optional context and application specific information, see [[hkdf()]]
* @return string the encrypted data
* @see decryptByKey()
* @see encryptByPassword()
*/
public function encryptByKey($data, $inputKey, $info = null)
{
return $this->encrypt($data, false, $inputKey, $info);
}
/**
* Verifies and decrypts data encrypted with [[encryptByPassword()]].
* @param string $data the encrypted data to decrypt
* @param string $password the password to use for decryption
* @return bool|string the decrypted data or false on authentication failure
* @see encryptByPassword()
*/
public function decryptByPassword($data, $password)
{
return $this->decrypt($data, true, $password, null);
}
/**
* Verifies and decrypts data encrypted with [[encryptByKey()]].
* @param string $data the encrypted data to decrypt
* @param string $inputKey the input to use for encryption and authentication
* @param string $info optional context and application specific information, see [[hkdf()]]
* @return bool|string the decrypted data or false on authentication failure
* @see encryptByKey()
*/
public function decryptByKey($data, $inputKey, $info = null)
{
return $this->decrypt($data, false, $inputKey, $info);
}
/**
* Encrypts data.
*
* @param string $data data to be encrypted
* @param bool $passwordBased set true to use password-based key derivation
* @param string $secret the encryption password or key
* @param string|null $info 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
* @throws Exception on OpenSSL not loaded
* @throws Exception on OpenSSL error
* @see decrypt()
*/
protected function encrypt($data, $passwordBased, $secret, $info)
{
if (!extension_loaded('openssl')) {
throw new Exception('Encryption requires the OpenSSL PHP extension');
}
if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
throw new Exception($this->cipher . ' is not an allowed cipher');
}
list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
$keySalt = $this->generateRandomKey($keySize);
if ($passwordBased) {
$key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
} else {
$key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
}
$iv = $this->generateRandomKey($blockSize);
$encrypted = openssl_encrypt($data, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
if ($encrypted === false) {
throw new Exception('OpenSSL failure on encryption: ' . openssl_error_string());
}
$authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
$hashed = $this->hashData($iv . $encrypted, $authKey);
/*
* Output: [keySalt][MAC][IV][ciphertext]
* - keySalt is KEY_SIZE bytes long
* - MAC: message authentication code, length same as the output of MAC_HASH
* - IV: initialization vector, length $blockSize
*/
return $keySalt . $hashed;
}
/**
* Decrypts data.
*
* @param string $data encrypted data to be decrypted.
* @param bool $passwordBased set true to use password-based key derivation
* @param string $secret the decryption password or key
* @param string|null $info context/application specific information, @see encrypt()
*
* @return bool|string the decrypted data or false on authentication failure
* @throws Exception on OpenSSL not loaded
* @throws Exception on OpenSSL error
* @see encrypt()
*/
protected function decrypt($data, $passwordBased, $secret, $info)
{
if (!extension_loaded('openssl')) {
throw new Exception('Encryption requires the OpenSSL PHP extension');
}
if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
throw new Exception($this->cipher . ' is not an allowed cipher');
}
list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
$keySalt = StringHelper::byteSubstr($data, 0, $keySize);
if ($passwordBased) {
$key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
} else {
$key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
}
$authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
$data = $this->validateData(StringHelper::byteSubstr($data, $keySize, null), $authKey);
if ($data === false) {
return false;
}
$iv = StringHelper::byteSubstr($data, 0, $blockSize);
$encrypted = StringHelper::byteSubstr($data, $blockSize, null);
$decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
if ($decrypted === false) {
throw new Exception('OpenSSL failure on decryption: ' . openssl_error_string());
}
return $decrypted;
}
/**
* 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.
* @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
* @param string $inputKey the source key
* @param string $salt the random salt
* @param string $info 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)
* @param int $length length of the output key in bytes. If 0, the output key is
* the length of the hash algorithm output.
* @throws Exception when HMAC generation fails.
* @return string the derived key
*/
public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0)
{
if (function_exists('hash_hkdf')) {
$outputKey = hash_hkdf($algo, $inputKey, $length, $info, $salt);
if ($outputKey === false) {
throw new Exception('Invalid parameters to hash_hkdf()');
}
return $outputKey;
}
$test = @hash_hmac($algo, '', '', true);
if (!$test) {
throw new Exception('Failed to generate HMAC with hash algorithm: ' . $algo);
}
$hashLength = StringHelper::byteLength($test);
if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
$length = (int) $length;
}
if (!is_int($length) || $length < 0 || $length > 255 * $hashLength) {
throw new Exception('Invalid length');
}
$blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
if ($salt === null) {
$salt = str_repeat("\0", $hashLength);
}
$prKey = hash_hmac($algo, $inputKey, $salt, true);
$hmac = '';
$outputKey = '';
for ($i = 1; $i <= $blocks; $i++) {
$hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true);
$outputKey .= $hmac;
}
if ($length !== 0) {
$outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
}
return $outputKey;
}
/**
* Derives a key from the given password using the standard PBKDF2 algorithm.
* Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2)
* Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
* @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
* @param string $password the source password
* @param string $salt the random salt
* @param int $iterations the number of iterations of the hash algorithm. Set as high as
* possible to hinder dictionary password attacks.
* @param int $length 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
* @throws Exception when hash generation fails due to invalid params given.
*/
public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
{
if (function_exists('hash_pbkdf2')) {
$outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
if ($outputKey === false) {
throw new Exception('Invalid parameters to hash_pbkdf2()');
}
return $outputKey;
}
// todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()?
$test = @hash_hmac($algo, '', '', true);
if (!$test) {
throw new Exception('Failed to generate HMAC with hash algorithm: ' . $algo);
}
if (is_string($iterations) && preg_match('{^\d{1,16}$}', $iterations)) {
$iterations = (int) $iterations;
}
if (!is_int($iterations) || $iterations < 1) {
throw new Exception('Invalid iterations');
}
if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
$length = (int) $length;
}
if (!is_int($length) || $length < 0) {
throw new Exception('Invalid length');
}
$hashLength = StringHelper::byteLength($test);
$blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
$outputKey = '';
for ($j = 1; $j <= $blocks; $j++) {
$hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true);
$xorsum = $hmac;
for ($i = 1; $i < $iterations; $i++) {
$hmac = hash_hmac($algo, $hmac, $password, true);
$xorsum ^= $hmac;
}
$outputKey .= $xorsum;
}
if ($length !== 0) {
$outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
}
return $outputKey;
}
/**
* 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()]] or [[encryptByPassword()]]
* as those methods perform the task.
* @param string $data the data to be protected
* @param string $key the secret key to be used for generating hash. Should be a secure
* cryptographic key.
* @param bool $rawHash 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
* @throws Exception when HMAC generation fails.
* @see validateData()
* @see generateRandomKey()
* @see hkdf()
* @see pbkdf2()
*/
public function hashData($data, $key, $rawHash = false)
{
$hash = hash_hmac($this->macHash, $data, $key, $rawHash);
if (!$hash) {
throw new Exception('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
}
return $hash . $data;
}
/**
* Validates if the given data is tampered.
* @param string $data the data to be validated. The data must be previously
* generated by [[hashData()]].
* @param string $key 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.
* @param bool $rawHash 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|false the real data with the hash stripped off. False if the data is tampered.
* @throws Exception when HMAC generation fails.
* @see hashData()
*/
public function validateData($data, $key, $rawHash = false)
{
$test = @hash_hmac($this->macHash, '', '', $rawHash);
if (!$test) {
throw new Exception('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
}
$hashLength = StringHelper::byteLength($test);
if (StringHelper::byteLength($data) >= $hashLength) {
$hash = StringHelper::byteSubstr($data, 0, $hashLength);
$pureData = StringHelper::byteSubstr($data, $hashLength, null);
$calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);
if ($this->compareString($hash, $calculatedHash)) {
return $pureData;
}
}
return false;
}
private $_useLibreSSL;
private $_randomFile;
/**
* Generates specified number of random bytes.
* Note that output may not be ASCII.
* @see generateRandomString() if you need a string.
*
* @param int $length the number of bytes to generate
* @return string the generated random bytes
* @throws Exception if wrong length is specified
* @throws Exception on failure.
*/
public function generateRandomKey($length = 32)
{
if (!is_int($length)) {
throw new Exception('First parameter ($length) must be an integer');
}
if ($length < 1) {
throw new Exception('First parameter ($length) must be greater than 0');
}
// always use random_bytes() if it is available
if (function_exists('random_bytes')) {
return random_bytes($length);
}
// The recent LibreSSL RNGs are faster and likely better than /dev/urandom.
// Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.
// https://bugs.php.net/bug.php?id=71143
if ($this->_useLibreSSL === null) {
$this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT')
&& preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
&& (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105;
}
// Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
// of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows.
if ($this->_useLibreSSL
|| (
DIRECTORY_SEPARATOR !== '/'
&& substr_compare(PHP_OS, 'win', 0, 3, true) === 0
&& function_exists('openssl_random_pseudo_bytes')
)
) {
$key = openssl_random_pseudo_bytes($length, $cryptoStrong);
if ($cryptoStrong === false) {
throw new Exception(
'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
);
}
if ($key !== false && StringHelper::byteLength($key) === $length) {
return $key;
}
}
// mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads
// CryptGenRandom on Windows. Elsewhere it directly reads /dev/urandom.
if (function_exists('mcrypt_create_iv')) {
$key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
if (StringHelper::byteLength($key) === $length) {
return $key;
}
}
// If not on Windows, try to open a random device.
if ($this->_randomFile === null && DIRECTORY_SEPARATOR === '/') {
// urandom is a symlink to random on FreeBSD.
$device = PHP_OS === 'FreeBSD' ? '/dev/random' : '/dev/urandom';
// Check random device for special character device protection mode. Use lstat()
// instead of stat() in case an attacker arranges a symlink to a fake device.
$lstat = @lstat($device);
if ($lstat !== false && ($lstat['mode'] & 0170000) === 020000) {
$this->_randomFile = fopen($device, 'rb') ?: null;
if (is_resource($this->_randomFile)) {
// Reduce PHP stream buffer from default 8192 bytes to optimize data
// transfer from the random device for smaller values of $length.
// This also helps to keep future randoms out of user memory space.
$bufferSize = 8;
if (function_exists('stream_set_read_buffer')) {
stream_set_read_buffer($this->_randomFile, $bufferSize);
}
// stream_set_read_buffer() isn't implemented on HHVM
if (function_exists('stream_set_chunk_size')) {
stream_set_chunk_size($this->_randomFile, $bufferSize);
}
}
}
}
if (is_resource($this->_randomFile)) {
$buffer = '';
$stillNeed = $length;
while ($stillNeed > 0) {
$someBytes = fread($this->_randomFile, $stillNeed);
if ($someBytes === false) {
break;
}
$buffer .= $someBytes;
$stillNeed -= StringHelper::byteLength($someBytes);
if ($stillNeed === 0) {
// Leaving file pointer open in order to make next generation faster by reusing it.
return $buffer;
}
}
fclose($this->_randomFile);
$this->_randomFile = null;
}
throw new Exception('Unable to generate a random key');
}
/**
* Generates a random string of specified length.
* The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
*
* @param int $length the length of the key in characters
* @return string the generated random key
* @throws Exception on failure.
*/
public function generateRandomString($length = 32)
{
if (!is_int($length)) {
throw new Exception('First parameter ($length) must be an integer');
}
if ($length < 1) {
throw new Exception('First parameter ($length) must be greater than 0');
}
$bytes = $this->generateRandomKey($length);
return substr(StringHelper::base64UrlEncode($bytes), 0, $length);
}
/**
* 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()]]. 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
* }
* ```
*
* @param string $password The password to be hashed.
* @param int $cost 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)
* @throws Exception on bad password parameter or cost parameter.
* @see validatePassword()
*/
public function generatePasswordHash($password, $cost = null)
{
if ($cost === null) {
$cost = $this->passwordHashCost;
}
if (function_exists('password_hash')) {
/* @noinspection PhpUndefinedConstantInspection */
return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
}
$salt = $this->generateSalt($cost);
$hash = crypt($password, $salt);
// strlen() is safe since crypt() returns only ascii
if (!is_string($hash) || strlen($hash) !== 60) {
throw new Exception('Unknown error occurred while generating hash.');
}
return $hash;
}
/**
* Verifies a password against a hash.
* @param string $password The password to verify.
* @param string $hash The hash to verify the password against.
* @return bool whether the password is correct.
* @throws Exception on bad password/hash parameters or if crypt() with Blowfish hash is not available.
* @see generatePasswordHash()
*/
public function validatePassword($password, $hash)
{
if (!is_string($password) || $password === '') {
throw new Exception('Password must be a string and cannot be empty.');
}
if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches)
|| $matches[1] < 4
|| $matches[1] > 30
) {
throw new Exception('Hash is invalid.');
}
if (function_exists('password_verify')) {
return password_verify($password, $hash);
}
$test = crypt($password, $hash);
$n = strlen($test);
if ($n !== 60) {
return false;
}
return $this->compareString($test, $hash);
}
/**
* Generates a salt that can be used to generate a password hash.
*
* The PHP [crypt()](http://php.net/manual/en/function.crypt.php) 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".
*
* @param int $cost the cost parameter
* @return string the random salt value.
* @throws Exception if the cost parameter is out of the range of 4 to 31.
*/
protected function generateSalt($cost = 13)
{
$cost = (int) $cost;
if ($cost < 4 || $cost > 31) {
throw new Exception('Cost must be between 4 and 31.');
}
// Get a 20-byte random string
$rand = $this->generateRandomKey(20);
// Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter.
$salt = sprintf('$2y$%02d$', $cost);
// Append the random salt data in the required base64 format.
$salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
return $salt;
}
/**
* Performs string comparison using timing attack resistant approach.
* @see http://codereview.stackexchange.com/questions/13512
* @param string $expected string to compare.
* @param string $actual user-supplied string.
* @return bool whether strings are equal.
*/
public function compareString($expected, $actual)
{
$expected .= "\0";
$actual .= "\0";
$expectedLength = StringHelper::byteLength($expected);
$actualLength = StringHelper::byteLength($actual);
$diff = $expectedLength - $actualLength;
for ($i = 0; $i < $actualLength; $i++) {
$diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
}
return $diff === 0;
}
/**
* 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.
* @param string $token An unmasked token.
* @return string A masked token.
* @since 2.0.12
*/
public function maskToken($token)
{
// The number of bytes in a mask is always equal to the number of bytes in a token.
$mask = $this->generateRandomKey(StringHelper::byteLength($token));
return StringHelper::base64UrlEncode($mask . ($mask ^ $token));
}
/**
* Unmasks a token previously masked by `maskToken`.
* @param string $maskedToken A masked token.
* @return string An unmasked token, or an empty string in case of token format is invalid.
* @since 2.0.12
*/
public function unmaskToken($maskedToken)
{
$decoded = StringHelper::base64UrlDecode($maskedToken);
$length = StringHelper::byteLength($decoded) / 2;
// Check if the masked token has an even length.
if (!is_int($length)) {
return '';
}
return StringHelper::byteSubstr($decoded, $length, $length) ^ StringHelper::byteSubstr($decoded, 0, $length);
}
}
/**
* BaseStringHelper provides concrete implementation for [[StringHelper]].
*
* Do not use BaseStringHelper. Use [[StringHelper]] instead.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alex Makarov <sam@rmcreative.ru>
* @since 2.0
*/
class StringHelper
{
/**
* Returns the number of bytes in the given string.
* This method ensures the string is treated as a byte array by using `mb_strlen()`.
* @param string $string the string being measured for length
* @return int the number of bytes in the given string.
*/
public static function byteLength($string)
{
return mb_strlen($string, '8bit');
}
/**
* Returns the portion of string specified by the start and length parameters.
* This method ensures the string is treated as a byte array by using `mb_substr()`.
* @param string $string the input string. Must be one character or longer.
* @param int $start the starting position
* @param int $length the desired portion length. If not specified or `null`, there will be
* no limit on length i.e. the output will be until the end of the string.
* @return string the extracted part of string, or FALSE on failure or an empty string.
* @see http://www.php.net/manual/en/function.substr.php
*/
public static function byteSubstr($string, $start, $length = null)
{
return mb_substr($string, $start, $length === null ? mb_strlen($string, '8bit') : $length, '8bit');
}
/**
* Returns the trailing name component of a path.
* This method is similar to the php function `basename()` except that it will
* treat both \ and / as directory separators, independent of the operating system.
* This method was mainly created to work on php namespaces. When working with real
* file paths, php's `basename()` should work fine for you.
* Note: this method is not aware of the actual filesystem, or path components such as "..".
*
* @param string $path A path string.
* @param string $suffix If the name component ends in suffix this will also be cut off.
* @return string the trailing name component of the given path.
* @see http://www.php.net/manual/en/function.basename.php
*/
public static function basename($path, $suffix = '')
{
if (($len = mb_strlen($suffix)) > 0 && mb_substr($path, -$len) === $suffix) {
$path = mb_substr($path, 0, -$len);
}
$path = rtrim(str_replace('\\', '/', $path), '/\\');
if (($pos = mb_strrpos($path, '/')) !== false) {
return mb_substr($path, $pos + 1);
}
return $path;
}
/**
* Returns parent directory's path.
* This method is similar to `dirname()` except that it will treat
* both \ and / as directory separators, independent of the operating system.
*
* @param string $path A path string.
* @return string the parent directory's path.
* @see http://www.php.net/manual/en/function.basename.php
*/
public static function dirname($path)
{
$pos = mb_strrpos(str_replace('\\', '/', $path), '/');
if ($pos !== false) {
return mb_substr($path, 0, $pos);
}
return '';
}
/**
* Check if given string starts with specified substring.
* Binary and multibyte safe.
*
* @param string $string Input string
* @param string $with Part to search inside the $string
* @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the starting of the string in order to get a true value.
* @return bool Returns true if first input starts with second input, false otherwise
*/
public static function startsWith($string, $with, $caseSensitive = true)
{
if (!$bytes = static::byteLength($with)) {
return true;
}
if ($caseSensitive) {
return strncmp($string, $with, $bytes) === 0;
}
$encoding = 'UTF-8';
return mb_strtolower(mb_substr($string, 0, $bytes, '8bit'), $encoding) === mb_strtolower($with, $encoding);
}
/**
* Check if given string ends with specified substring.
* Binary and multibyte safe.
*
* @param string $string Input string to check
* @param string $with Part to search inside of the $string.
* @param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the ending of the string in order to get a true value.
* @return bool Returns true if first input ends with second input, false otherwise
*/
public static function endsWith($string, $with, $caseSensitive = true)
{
if (!$bytes = static::byteLength($with)) {
return true;
}
if ($caseSensitive) {
// Warning check, see http://php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
if (static::byteLength($string) < $bytes) {
return false;
}
return substr_compare($string, $with, -$bytes, $bytes) === 0;
}
$encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
return mb_strtolower(mb_substr($string, -$bytes, mb_strlen($string, '8bit'), '8bit'), $encoding) === mb_strtolower($with, $encoding);
}
/**
* Explodes string into array, optionally trims values and skips empty ones.
*
* @param string $string String to be exploded.
* @param string $delimiter Delimiter. Default is ','.
* @param mixed $trim Whether to trim each element. Can be:
* - boolean - to trim normally;
* - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
* - callable - will be called for each value instead of trim. Takes the only argument - value.
* @param bool $skipEmpty Whether to skip empty strings between delimiters. Default is false.
* @return array
* @since 2.0.4
*/
public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
{
$result = explode($delimiter, $string);
if ($trim) {
if ($trim === true) {
$trim = 'trim';
} elseif (!is_callable($trim)) {
$trim = function ($v) use ($trim) {
return trim($v, $trim);
};
}
$result = array_map($trim, $result);
}
if ($skipEmpty) {
// Wrapped with array_values to make array keys sequential after empty values removing
$result = array_values(array_filter($result, function ($value) {
return $value !== '';
}));
}
return $result;
}
/**
* Counts words in a string.
* @since 2.0.8
*
* @param string $string
* @return int
*/
public static function countWords($string)
{
return count(preg_split('/\s+/u', $string, null, PREG_SPLIT_NO_EMPTY));
}
/**
* Returns string representation of number value with replaced commas to dots, if decimal point
* of current locale is comma.
* @param int|float|string $value
* @return string
* @since 2.0.11
*/
public static function normalizeNumber($value)
{
$value = "$value";
$localeInfo = localeconv();
$decimalSeparator = isset($localeInfo['decimal_point']) ? $localeInfo['decimal_point'] : null;
if ($decimalSeparator !== null && $decimalSeparator !== '.') {
$value = str_replace($decimalSeparator, '.', $value);
}
return $value;
}
/**
* Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
*
* > Note: Base 64 padding `=` may be at the end of the returned string.
* > `=` is not transparent to URL encoding.
*
* @see https://tools.ietf.org/html/rfc4648#page-7
* @param string $input the string to encode.
* @return string encoded string.
* @since 2.0.12
*/
public static function base64UrlEncode($input)
{
return strtr(base64_encode($input), '+/', '-_');
}
/**
* Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
*
* @see https://tools.ietf.org/html/rfc4648#page-7
* @param string $input encoded string.
* @return string decoded string.
* @since 2.0.12
*/
public static function base64UrlDecode($input)
{
return base64_decode(strtr($input, '-_', '+/'));
}
/**
* Safely casts a float to string independent of the current locale.
*
* The decimal separator will always be `.`.
* @param float|int $number a floating point number or integer.
* @return string the string representation of the number.
* @since 2.0.13
*/
public static function floatToString($number)
{
// . and , are the only decimal separators known in ICU data,
// so its safe to call str_replace here
return str_replace(',', '.', (string) $number);
}
}
复制代码
转载于:https://juejin.im/post/5b8915e1e51d45389f54f114
Yii项目Security加密解密类提取的更多相关文章
- Java常用的加密解密类(对称加密类)
Java常用的加密解密类 原文转载至:http://blog.csdn.net/wyc_cs/article/details/8793198 原创 2013年04月12日 14:33:35 1704 ...
- [C#] 常用工具类——加密解密类
using System; using System.Configuration; using System.Collections.Generic; using System.Text; using ...
- java文本文件加密解密类
原文:http://www.open-open.com/code/view/1420031154765 import java.awt.*; import java.awt.event.*; impo ...
- 对接携程供应商php加密解密类
php加密解密类 <?php class Aes{ private $key = '6b4d63211b4ba869'; private $iv = 'dbbf079b95004f65'; pu ...
- PHP针对数字的加密解密类,可直接使用
<?phpnamespace app;/** * 加密解密类 * 该算法仅支持加密数字.比较适用于数据库中id字段的加密解密,以及根据数字显示url的加密. * @author 深秋的竹子 * ...
- 生成二维码 加密解密类 TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型) COOKIE帮助类 数据类型转换 截取字符串 根据IP获取地点 生成随机字符 UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME 是否包含中文 生成秘钥方式之一 计算某一年 某一周 的起始时间和结束时间
生成二维码 /// <summary>/// 生成二维码/// </summary>public static class QRcodeUtils{private static ...
- AES对称加密解密类
import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.Se ...
- 一个java的DES加密解密类转换成C#
一个java的des加密解密代码如下: //package com.visionsky.util; import java.security.*; //import java.util.regex.P ...
- 推荐分享一个牛X的自定义PHP加密解密类
通俗点说,用它来进行加密,同一个字符串,每次进行加密,得出的结果都是不一样的,大大加强了数据安全性.同时还可设定加密后数据的有效期,简直牛掰了 #食用方法 将下面的第二份模块代码保存为 Mcrypt. ...
随机推荐
- Redis 笔记(三)—— LIST 常用命令
常用命令 命令 用例和描述 RPUSH RPUSH key value [value ...] —— 将一个或多个值推入列表的右端 LPUSH LPUSH key value [value ...] ...
- 个人博客如何申请ICP备案
目录 前言 一定要备案吗? 备案前的准备 域名 备案资料 备案服务号 如何申请ICP备案 备案成功之后 总结 关于博客的搭建 参考资料 推荐阅读 前言 前一段时间,博客域名在申请ICP备案,暂时不能访 ...
- 虚拟机的vmnet8网卡找不到了
不知道我设置了什么,在我于Linux中配置网络时发现怎么都不行,检查了一下发现用于NAT的网卡没有了. 我重启了电脑之后发现还是没有. 于是按照网上的办法在虚拟网络编辑器将其重置,如下图. 问题解决. ...
- (js描述的)数据结构[哈希表1.3](10)
1.哈希表的完善 1.容量质数(limit):需要恒为质数,来确保元素的均匀分布. 1)普通算法: 判断一个数是否为质数 function isPrime(num) { for (var i = 2; ...
- go 基础安装
一.安装: 1.下载GO的地址:https://golang.org/dl/ 点击安装包进行安装(linux直接解压) 设置环境变量(linux) 1. export GOROOT=$PATH:/pa ...
- MODIS系列之NDVI(MOD13Q1)三:.jdk文件配置+MRT安装
MRT(MODIS Reprojection Tool)简介: MODIS的全称为中分辨率成像光谱仪(Moderate-Resolution Imaging Spectroradiometer),是搭 ...
- 21.1 Math(数学运算)方法使用 、工具类
package day21_static.meathDemo; //Math: 包含一些基本的数学运算方法 //从api中搜Math,它都用的static修饰. public class MethDe ...
- 如何实现Jenkins 编译结果通知到QQ好友及QQ群组<很遗憾 2019年1月1日腾讯停止了webqq机器人的服务支持>
Jenkins-NotifyQQ NotifyQQ 运行于Docker 本文介绍mac 环境下实现Jenkins编译结果QQ即时通知 Jenkins 安装使用及iOS自动化打包,邮件通知请参考本人博客 ...
- docker深入学习
docker深入学习 一.容器的介绍和容器的发展史 为什么要学习容器? 在openstack之后,目前互联网最火热的技术莫过于docker容器了,早在2015年,京东技术备战双11就是使用了10万+D ...
- LCA Nearest Common Ancestors (很典型的例题)
A rooted tree is a well-known data structure in computer science and engineering. An example is show ...