Why doesn't echo openssl_random_pseudo_bytes(12)
print out anything but if I concatenate it with another string it does show the output? According to the manual the return type of openssl_random_pseudo_bytes
is a string so why is there a problem? I tried type casting it with (string)
and it didn't work.
Asked
Active
Viewed 1,153 times
0
-
[var_dump](http://php.net/manual/en/function.var-dump.php) is your friend. – random_user_name Aug 09 '13 at 00:01
1 Answers
0
The openssl_random_pseudo_bytes(...)
function returns a binary number in the form of a string (i.e. ASCII value(s)) of the specified length.
For example, one possible output of:
$number_of_bytes = 1;
$bin = openssl_random_pseudo_bytes($number_of_bytes, $cstrong);
$hex=bin2hex($bin);
$dec=hexdec($hex);
could be:
var_dump($bin); // string(1) "ã"
var_dump($hex); // string(2) "e3"
var_dump($dec); // int(227)
var_dump($cstrong); // bool(true)
Notes:
$dec
is an integer random value that can be equal to (at most) 2 ^ (8 * $number_of_bytes) - 1.- where one byte comprises 8 bits
- PHP has a integer overflow limitation of at most 2^31-1 or 2^63-1 bits (the limits of signed integers which use 4 bytes or 8 bytes depending on whether you have a 32 or 64 bit platform respectively) , after which it overflows / casts into a float value (potentially limiting precision).
- so calling with 4 (or 8) bytes, half of the time
$dec
would be a float
- so calling with 4 (or 8) bytes, half of the time
- At higher numbers of bytes, the
$bin
and$hex
values maintain their precision and accuracy (because all of the digits/bits are kept in a (variable length) string). openssl_random_pseudo_bytes
returnsfalse
when it fails.$cstrong!==true
indicatesopenssl_random_pseudo_bytes
did not return a result generated by a cryptographically strong algorithm. (http://php.net/openssl_random_pseudo_bytes)
Example Function (demonstrates handling a false
return value or when $cstrong is false)
class Random
{
public static function Get($number_of_bytes=4)
{
$binary_value = openssl_random_pseudo_bytes($number_of_bytes, $cstrong);
// Unable to produce a cryptographically strong value
if($binary_value==false || $cstrong!==true) return false; // failure
// other processing
$hexadecimal_value = bin2hex($binary_value);
$decimal_value = hexdec($hexadecimal_value);
// Returns a positive integer (or a float
// in the case of an integer overflow)
return $decimal_value;
}
}
manual: http://php.net/openssl_random_pseudo_bytes
Usage
echo Random::Get(12); // returns a large float value most of the time

dajon
- 2,350
- 1
- 16
- 17