Skip to content

Instantly share code, notes, and snippets.

@tom--
Created January 4, 2016 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tom--/990c0f72aee4fe5a502c to your computer and use it in GitHub Desktop.
Save tom--/990c0f72aee4fe5a502c to your computer and use it in GitHub Desktop.
Extends yii\base\Security::generateRandomKey() to use suspicious OpenSSL setups
<?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