Convert random values โ€‹โ€‹from / dev / urandom

As mentioned in the comments of mt_rand() , it is weak in security, and we should use / dev / urandom instead. My problem is that from urandom I get a binary string.

How to convert this binary string to 0-9a-zA-Z?

Looks like base_convert() is not working here.

+4
source share
4 answers

For write-only full function:

 function randomFromDev($len) { $fp = @fopen('/dev/urandom','rb'); $result = ''; if ($fp !== FALSE) { $result .= @fread($fp, $len); @fclose($fp); } else { trigger_error('Can not open /dev/urandom.'); } // convert from binary to string $result = base64_encode($result); // remove none url chars $result = strtr($result, '+/', '-_'); // Remove = from the end $result = str_replace('=', ' ', $result); return $result; } 
+3
source

You can use bin2hex to convert string to string. And PHP 7 random_bytes added urandom search.

 <?php $bytes = random_bytes(5); $str = bin2hex($bytes); var_dump($str); // string(10) "385e33f741" ?> 
+2
source

just use base64_encode($yourbinaryurandomstring)

with this result, you can, for example, use a hash function, for example sha1() or md5() , and everything should be fine. You donโ€™t even do any "=" conversion

I'm not quite sure that hash functions can read the binary string by themselves, just try.

+1
source

One way to use /dev/urandom is to use the uiniqid function, which should suit your needs.

However, if you need true random numbers, you are better off using /dev/random , since /dev/urandom is still a pseudo-random number generator that uses /dev/random for seed values.

Access to a stream of random numbers is not so difficult.

 <?php $r = unpack('v*', fread(fopen('/dev/random', 'r'),16)); $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', $r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000, $r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8]); ?> 

Obviously, this is not production code.

+1
source

Source: https://habr.com/ru/post/1385317/


All Articles