diff options
author | Josh Hoyt <josh@janrain.com> | 2005-12-27 20:21:11 +0000 |
---|---|---|
committer | Josh Hoyt <josh@janrain.com> | 2005-12-27 20:21:11 +0000 |
commit | 648a449acbcfd135bb2f10ccdab5296f1517be57 (patch) | |
tree | fcecd23922144dba96a2ea29bf0a5996f6e40cc1 /Net | |
parent | 3d7741dd544006039d074f74709cec8aea98a4be (diff) | |
download | php-openid-648a449acbcfd135bb2f10ccdab5296f1517be57.zip php-openid-648a449acbcfd135bb2f10ccdab5296f1517be57.tar.gz php-openid-648a449acbcfd135bb2f10ccdab5296f1517be57.tar.bz2 |
[project @ Documentation and removal of silly low-entropy entropy sources from CryptUtil]
Diffstat (limited to 'Net')
-rw-r--r-- | Net/OpenID/CryptUtil.php | 50 |
1 files changed, 30 insertions, 20 deletions
diff --git a/Net/OpenID/CryptUtil.php b/Net/OpenID/CryptUtil.php index 379f2d4..9249d5a 100644 --- a/Net/OpenID/CryptUtil.php +++ b/Net/OpenID/CryptUtil.php @@ -1,31 +1,41 @@ <?php -class Net_OpenID_CryptUtil { - function _getFourBytes() { - $x = mt_rand(); - - $sources = array( - time(), - getmypid(), - getmygid(), - getmyuid(), - disk_free_space(__FILE__) - ); - - foreach ($sources as $ent) { - $x ^= $ent; - mt_srand($x); - $x = mt_rand(); - } - return $x; - } +if (!defined(Net_OpenID_RAND_SOURCE)) { + /** + * The filename for a source of random bytes. Define this yourself if you + * have a different source of randomness. + */ + define('Net_OpenID_RAND_SOURCE', '/dev/urandom'); +} +/** + * Cryptographic utility functions + */ +class Net_OpenID_CryptUtil { + /** + * Get the specified number of random bytes. + * + * Attempts to use a cryptographically secure (not predictable) source of + * randomness if available. If there is no high-entropy randomness source + * available, it will fail. As a last resort, for non-critical systems, + * define <code>Net_OpenID_USE_INSECURE_RAND</code>, and the code will + * fall back on a pseudo-random number generator. + * + * @static + * @param int $num_bytes The length of the return value + * @return string $num_bytes random bytes + */ function getBytes($num_bytes) { $f = @fopen("/dev/urandom", "r"); if ($f === FALSE) { + if (!defined(Net_OpenID_USE_INSECURE_RAND)) { + trigger_error('Set Net_OpenID_USE_INSECURE_RAND to ' . + 'continue with insecure random.', + E_USER_ERROR); + } $bytes = ''; for ($i = 0; $i < $num_bytes; $i += 4) { - $bytes .= Net_OpenID_CryptUtil::_getFourBytes(); + $bytes .= pack('L', mt_rand()); } $bytes = substr($bytes, 0, $num_bytes); } else { |