Created
January 4, 2016 16:24
-
-
Save tom--/990c0f72aee4fe5a502c to your computer and use it in GitHub Desktop.
Extends yii\base\Security::generateRandomKey() to use suspicious OpenSSL setups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace yourapp; | |
use yii\helpers\StringHelper; | |
class Security extends \yii\base\Security | |
{ | |
/** | |
* Extends yii\base\Security::generateRandomKey() to use suspicious OpenSSL setups if | |
* all else fails. | |
* | |
* @inheritdoc | |
*/ | |
public function generateRandomKey($length = 32) | |
{ | |
try { | |
$key = parent::generateRandomKey($length); | |
if (!empty($key) && StringHelper::byteLength($key) === $length) { | |
return $key; | |
} | |
} catch (\Exception $ignore) { | |
$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; | |
} | |
} | |
throw new \Exception('Unable to generate a random key'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment