php - Viewing the returned string of openssl_random_psuedo_bytes() -
why doesn't echo openssl_random_pseudo_bytes(12)
print out if concatinate string show output? according the manual return type of openssl_random_pseudo_bytes
string why there problem? tried type casting (string)
, didn't work.
the openssl_random_pseudo_bytes(...)
function returns binary number in form of string (i.e. ascii value(s)) of specified length.
for example, 1 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
integer random value can equal (at most) 2 ^ (8 * $number_of_bytes) - 1.- where 1 byte comprises 8 bits
- php has integer overflow limitation of @ 2^31-1 or 2^63-1 bits (the limits of signed integers use 4 bytes or 8 bytes depending on whether have 32 or 64 bit platform respectively) , after overflows / casts float value (potentially limiting precision).
- so calling 4 (or 8) bytes, half of time
$dec
float
- so calling 4 (or 8) bytes, half of time
- at higher numbers of bytes,
$bin
,$hex
values maintain precision , accuracy (because of digits/bits kept in (variable length) string). openssl_random_pseudo_bytes
returnsfalse
when fails.$cstrong!==true
indicatesopenssl_random_pseudo_bytes
did not return result generated cryptographically strong algorithm. (http://php.net/openssl_random_pseudo_bytes)
example function (demonstrates handling false
return value or when $cstrong false)
class random { public static function get($number_of_bytes=4) { $binary_value = openssl_random_pseudo_bytes($number_of_bytes, $cstrong); // unable produce 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 positive integer (or float // in case of integer overflow) return $decimal_value; } }
manual: http://php.net/openssl_random_pseudo_bytes
usage
echo random::get(12); // returns large float value of time
Comments
Post a Comment