4 * CryptUtil: A suite of wrapper utility functions for the OpenID
9 * LICENSE: See the COPYING file included in this distribution.
13 * @author JanRain, Inc. <openid@janrain.com>
14 * @copyright 2005-2008 Janrain, Inc.
15 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
18 if (!defined('Auth_OpenID_RAND_SOURCE')) {
20 * The filename for a source of random bytes. Define this yourself
21 * if you have a different source of randomness.
23 define('Auth_OpenID_RAND_SOURCE', '/dev/urandom');
26 class Auth_OpenID_CryptUtil {
28 * Get the specified number of random bytes.
30 * Attempts to use a cryptographically secure (not predictable)
31 * source of randomness if available. If there is no high-entropy
32 * randomness source available, it will fail. As a last resort,
33 * for non-critical systems, define
34 * <code>Auth_OpenID_RAND_SOURCE</code> as <code>null</code>, and
35 * the code will fall back on a pseudo-random number generator.
37 * @param int $num_bytes The length of the return value
38 * @return string $bytes random bytes
40 static function getBytes($num_bytes)
45 if (Auth_OpenID_RAND_SOURCE === null) {
48 $f = @fopen(Auth_OpenID_RAND_SOURCE, "r");
50 $msg = 'Define Auth_OpenID_RAND_SOURCE as null to ' .
51 ' continue with an insecure random number generator.';
52 trigger_error($msg, E_USER_ERROR);
59 for ($i = 0; $i < $num_bytes; $i += 4) {
60 $bytes .= pack('L', mt_rand());
62 $bytes = substr($bytes, 0, $num_bytes);
64 $bytes = fread($f, $num_bytes);
70 * Produce a string of length random bytes, chosen from chrs. If
71 * $chrs is null, the resulting string may contain any characters.
73 * @param integer $length The length of the resulting
74 * randomly-generated string
75 * @param string $chrs A string of characters from which to choose
76 * to build the new string
77 * @return string $result A string of randomly-chosen characters
80 static function randomString($length, $population = null)
82 if ($population === null) {
83 return Auth_OpenID_CryptUtil::getBytes($length);
86 $popsize = strlen($population);
89 $msg = 'More than 256 characters supplied to ' . __FUNCTION__;
90 trigger_error($msg, E_USER_ERROR);
93 $duplicate = 256 % $popsize;
96 for ($i = 0; $i < $length; $i++) {
98 $n = ord(Auth_OpenID_CryptUtil::getBytes(1));
99 } while ($n < $duplicate);
102 $str .= $population[$n];
108 static function constEq($s1, $s2)
110 if (strlen($s1) != strlen($s2)) {
115 $length = strlen($s1);
116 for ($i = 0; $i < $length; $i++) {
117 $result &= ($s1[$i] == $s2[$i]);